将值插入子查询中

时间:2015-05-27 19:33:27

标签: mysql sql

我正在尝试将值'1'插入到子查询的每个结果的'isTransfer'列中,但它不起作用。这是我选择行的查询:

select r.* 
from players r 
inner join ( 
   select name, rating, max(id) id 
   from players group by name, rating 
   having count(distinct club) > 1 
   ) 
q on r.name = q.name and r.rating = q.rating and r.id = q.id

这就是我要做的事情:

INSERT INTO 'isTransfer' VALUES '1' WHERE
(select r.* 
    from players r 
    inner join ( 
       select name, rating, max(id) id 
       from players group by name, rating 
       having count(distinct club) > 1 
       ) 
    q on r.name = q.name and r.rating = q.rating and r.id = q.id)

2 个答案:

答案 0 :(得分:3)

对于此任务,您需要执行UPDATE查询。此外,您不能像这样使用WHERE子句,您将收到错误。而是,更改where子句以查看子查询返回主键的位置。它看起来像这样:

UPDATE myTable
SET isTransfer = 1
WHERE primaryKey IN [mySubquery];

您需要确保子查询的SELECT中唯一的列是主键,否则会出现无效的操作数计数错误。

关于评论中的查询,JOIN不是必需的。相反,只需从子查询中获取不同的id值,如下所示:

SELECT DISTINCT id
FROM(
   SELECT name, rating, MAX(id) AS id
   FROM players
   GROUP BY name, rating
   HAVING COUNT(DISTINCT club) > 1) q

然后,该查询作为您的IN操作数。

答案 1 :(得分:2)

假设玩家表中的id是唯一的:

update players r inner join
       (select name, rating, max(id) as id 
        from players p
        group by name, rating 
        having count(distinct club) > 1 
       ) nr
       on r.id = nr.id
    set isTransfer = 1;