MySQL查询帮助(半独特结果)

时间:2010-11-10 22:36:41

标签: sql mysql

user_id | user_destination | user_date_out | user_date_in | user_purpose | uid
0095    | NYC              | 2010-11-25    | 2010-11-26   | Work         | 1
0105    | Seattle          | 2010-11-15    | 2010-11-20   | Work         | 2
0095    | Home             | 2010-11-10    | 2010-11-11   | Personal     | 3
0123    | Nashville        | 2010-11-10    | 2010-11-12   | Doctober     | 4

我在MySQL表中有上述数据。我需要一个查询,如果它是该user_id的最新user_date_out,将输出该行。很难解释,但应该通过查询显示的行是uid 2,3和4(UID 1会因为user_date_out比同一用户的UID 3“更旧”而下降。谁能帮我这个?提前谢谢!

编辑:我使用以下查询解决了这个问题:

SELECT *
FROM `table`
WHERE `uid` = (
    SELECT `uid`
    FROM `table` as `alt`
    WHERE `alt`.`user_id` = `table`.`user_id`
    ORDER BY `user_date_out`
    LIMIT 1
)
ORDER BY `user_date_out`

2 个答案:

答案 0 :(得分:3)

按要求

SELECT *
FROM `table`
WHERE `uid` = (
    SELECT `uid`
    FROM `table` as `alt`
    WHERE `alt`.`user_id` = `table`.`user_id`
    ORDER BY `user_date_out`
    LIMIT 1
)
ORDER BY `user_date_out`

答案 1 :(得分:1)

SELECT t.*, a_subquery.min_user_date_out
  FROM your_table t
       JOIN (SELECT user_id, MIN(user_date_out) AS min_user_date_out 
               FROM your_table
           GROUP BY user_id) a_subquery
       ON a_subquery.min_user_date_out = t.user_date_out 
      AND a_subquery.user_id = t.user_id

由于MySQL有时会出现子查询问题,因此这里的自相关查询与自我排除连接相同:

SELECT t.*
  FROM your_table t
       LEFT JOIN your_table t2 
       ON t.user_id = t2.user_id
       AND t.user_date_out > t2.user_date_out
 WHERE t2.user_id IS NULL

请注意,如果给定user_date_out的{​​{1}}中有多个user_id,则这两个查询都无效。