如何使用单个查询更新 MySQL 中的单列和多行


how to update single column and multiple rows in mysql using single query

MYSQL table -> T(player,id)

我正在尝试为相同(只有一个)id 和 10 个不同的玩家更新此 MYSQL 表。我做到了。

for($k=0;$k<10;$k++)
    {       
       echo $newPlayer[$k];
       $que = "UPDATE `players` SET `player`='".$newPlayer[$k]."' WHERE `id`='".$id."'";
       $db_con->exec($que);
    }

当我回显数组$newPlayer时,它会显示正确的值,因此查询不起作用的原因。

应将 11 行添加到表

"T"中,其中包含 11 个不同的玩家值和相同的 id 值。但只有一个玩家值被添加到表中。为什么??

update 语句用于更新数据,而不是用于插入数据。因此,使用更新,您只能更改表上已有的内容,不会创建任何新内容。

如果要插入新数据,则应使用insert语句。

使用您发布的命令,您要对数据库说

嘿,伙计使用值更改属性player '".$newPlayer[$k]."' 其中表playearid '".$id."'"

因此,正如此处评论中所讨论的,对您来说是一个更好的解决方案:

update players p, 
  (select id, player, substring_index( substring_index(lst, ',', idx), ',', -1) as pl
     from (select p.*, @number := @number+1 as idx, lst 
             from players p,
                 (select @number := 0 as nb) n,
                 (select 'i,j,k,l,m,n,o,p' as lst) lst) x ) a 
set p.player = a.pl
where p.id = a.id 
  and p.player = a.player

但是对于 PHP,您必须将数组$newPlayer为由,分隔的字符串,中间没有空格。

像这样:

$newNames = implode(",",$newPlayer);
 $que = "update players p, 
      (select id, player, substring_index( substring_index(lst, ',', idx), ',', -1) as pl
         from (select p.*, @number := @number+1 as idx, lst 
                 from players p,
                     (select @number := 0 as nb) n,
                     (select '$newNames' as lst) lst) x ) a 
    set p.player = a.pl
    where p.id = a.id 
      and p.player = a.player";
$db_con->exec($que);

有了这个,您将不需要for