如果第一个条目在任何行中不存在,如何更新第一个条目的值?

时间:2015-09-07 22:21:07

标签: mysql

我有一个体重记录表:

resources :users do
  collection do
    # creates /users/tags
    get :tags
  end
end

每个用户在第一次进入'Y'时必须有开始权重标记,但有些用户没有,我想设置它。

我可以这样选择这些用户:

id     userid   weight   is_start_weight
3      10       100      Y
5      10       98       N
7      11       120      N
9      11       115      N

问题是如何将SELECT p.userid FROM weight_tracker_log p WHERE NOT EXISTS ( SELECT s.userid FROM weight_tracker_log s WHERE p.userid = s.userid AND s.is_start_weight = 'Y' ) 标志更新为'Y'?第一个用户的条目,最低is_start_weight必须更新。

可能是我的选择错了,也许我应该将每个用户的第一个条目更新为'Y'?

2 个答案:

答案 0 :(得分:1)

您可以使用以下查询为每个用户设置最低ID:

update weight_tracker_log wtl join
       (select userid, min(id) as minid
        from weight_tracker_log
        group by userid
       ) u
       on wtl.userid = u.userid and wtl.id = u.minid
    set is_start_weight = 'Y'
    where wtl.is_start_weight <> 'Y';

编辑:

如果现有用户可以在非最小的ID上具有“Y”权重,则:

update weight_tracker_log wtl join
       (select userid, min(id) as minid,
               max(is_start_weight = 'Y') as has_y
        from weight_tracker_log
        group by userid
       ) u
       on wtl.userid = u.userid and wtl.id = u.minid and has_y = 0
    set is_start_weight = 'Y';

答案 1 :(得分:0)

您正在寻找的是更新联接查询。尝试

    update weight_tracker_log 
    inner join (
    SELECT min(p.id) id, p.userid
    FROM weight_tracker_log p
    WHERE NOT EXISTS (
        SELECT s.userid
        FROM weight_tracker_log s
        WHERE p.userid = s.userid AND s.is_start_weight = 'Y'
    )
    group by p.userid
    ) missing
    on weight_tracker_log.id = missing.id
    set weight_tracker_log.is_start_weight = 'Y'

请参阅。 https://www.google.com.au/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=mysql%20update%20join