开发者

sql update only the oldest of a many-to-one association

Given the tables in MySQL 5.0:

clients
=======
id  int

users
=====
id         int
client_id  int
is_primary tinyint

A client can have many users. I want to update users.is_primary = 1 for only the smallest users.id per users.client_id

For example, given these users:

users
id   client_id    is_primary
============================
1    1            0
2    1            0
3    2            0
4    2            0
5    3            0

I want to end up with:

users
id   client_id    is_primary
============================
1    1         开发者_如何学运维   1
2    1            0
3    2            1
4    2            0
5    3            1

Is there a way to write an update statement to do so?


update users 
set is_primary = 1
where id in (select * from (select min(id) from users group by client_id) as t)


Alternatively you should be able to use the join like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜