将mysql数据复制到同一个表中


copy mysql data to same the same table

我需要能够将所有没有userid的行复制到userid等于1的同一个表中。这是我的代码:(当我运行它时,它不起作用),它确实使用echo显示items字段和widget id字段。但它不插入数据。有什么建议

    $sql=("SELECT * from options WHERE userid='' ");
    $resultat= mysql_query($sql);
    while($row = mysql_fetch_array($resultat))
  {
     $userid="1";
    echo $items.$widgetid."<br>";
      $widgetid = $row['widgetid'];
      $items = $row['items'];
       $stats = $row['stats'];
      $upd=("INSERT INTO options (userid, widgetid, items,stats)
VALUES ('$userid', '$widgetid','$items', '$stats')");
mysql_query($upd);
      }
INSERT INTO options 
SELECT '1' AS userid, widgetid, items, stats 
FROM options
WHERE userid = ''

假设这是您表中列的顺序。

create table newTable like oldTable;
insert into newTable
select * from oldTable
where userid = '';

但也许你真的只需要像Naveen说的那样更新?

我认为您只需要更新userid=''所在的行

update options 
set userid=1 
where userid='';

$upd=("INSERT INTO options (userid, widgetid, items,stats)
 select 1, widgetid, stats from options
 where userid='' ");

在PHP 中使用以下代码段

$upd= (
       "INSERT INTO 
        options (userid, widgetid, items,stats) 
        VALUES (1, '". $widgetid ."' , '". $items ."' , '". $stats ."')
       "
      );