SQL-在另一列中发现重复值时在另一列上进行过滤

时间:2019-12-04 00:23:17

标签: mysql sql

假设我有两个表,一个用户表和一个日志表

用户表包含以下列:ID,名称

日志表具有以下列:id,user_id(User.id上的外键),last_updated_date,first_created_date。一个用户可以有很多日志,但是对我们来说最重要的用户日志是该用户最早的first_created_date日期的日志。

有人可以帮我制定一个查询,以便它返回具有属于该用户的日志的first_created_date最早的用户ID的100个列表吗?

查看下表,应返回的user_id为1和2。由于user_id 1具有最早的日志是2019年1月1日。而且由于user_id 2具有第二最早的日志(在其余用户中)这是2019年2月1日。

User Table
+----+-------+
| id | name  |
+----+-------+
| 1  | bob   |
+----+-------+
| 2  | carl  |
+----+-------+
| 3  | sandy |
+----+-------+



Log Table
+----+---------+-------------------+--------------------+
| id | user_id | last_updated_date | first_created_date |
+----+---------+-------------------+--------------------+
|  1 |       1 | not important     | Jan 1, 2019        |
|  2 |       1 | not important     | Jan 2, 2019        |
|  3 |       1 | not important     | Dec 3, 2019        |
|  4 |       2 | not important     | Feb 2, 2019        |
|  5 |       2 | not important     | Dec 3, 2019        |
|  6 |       3 | not important     | Mar 2, 2019        |
|  7 |       3 | not important     | Dec 3, 2019        | 
+----+---------+-------------------+--------------------+

1 个答案:

答案 0 :(得分:0)

您可以汇总并使用order bylimit

select user_id
from log 
group by user_id
order by min(first_created_date)
limit 2  -- or limit 100?