MySQL更新特定列

时间:2017-02-28 03:19:02

标签: php mysql sql

我们说我有一张如下表:

id user_id   name   custom_field     status
1    123     lee     firstname         1
2    123     tan     lastname          1
3    123     chan     firstname        1
4    123     jackie   lastname         1
5    123     justin   firstname        0
6    123     wong     lastname         0
7    223     kevin    firstname        1
8    223     riley    lastname         1
9    223      john    firtname         1
10   223      poh     lastname         1

我想要做的是,foreach user_id我想确保只有1个firstname和1个lastname的状态1。 (所以基本上我想通过id desc订购,并将那些不在前2名的人更新状态1到0)。我应该用什么sql脚本来完成这个?

1 个答案:

答案 0 :(得分:2)

您可以使用update查询执行此操作,例如:

update t join
       (select userid,
               max(case when custom_field = 'firstname' then id end) as maxid_first,
               max(case when custom_field = 'lastname' then id end) as maxid_last
        from t
        group by userid
       ) tt
       on tt.userid = t.userid and t.id not in (tt.maxid_first, tt.maxid_last)
    set status = 0;

编辑:

以上并不保证至少有一个“1”。为此:

update t join
       (select userid,
               max(case when custom_field = 'firstname' then id end) as maxid_first,
               max(case when custom_field = 'lastname' then id end) as maxid_last
        from t
        group by userid
       ) tt
       on tt.userid = t.userid
    set status = (t.id in (tt.maxid_first, tt.maxid_last));