鉴于MySQL 5.0中的表:
clients
=======
id int
users
=====
id int
client_id int
is_primary tinyint
客户端可以有很多用户。我想更新users.is_primary = 1只针对最小的users.id per users.client_id
例如,给定这些用户:
users
id client_id is_primary
============================
1 1 0
2 1 0
3 2 0
4 2 0
5 3 0
我想最终:
users
id client_id is_primary
============================
1 1 1
2 1 0
3 2 1
4 2 0
5 3 1
有没有办法编写更新语句来执行此操作?
答案 0 :(得分:4)
update users
set is_primary = 1
where id in (select * from (select min(id) from users group by client_id) as t)
答案 1 :(得分:4)
或者你应该可以像这样使用连接:
UPDATE users
INNER JOIN (
SELECT MIN(id) AS id
FROM users
GROUP BY client_id
) m ON users.id = m.id
SET users.is_primary = 1