我有三个表,我需要找到用户作为主持人和访客加入的事件的第一个日期和最后(最近)日期。换句话说,返回的数据应如下所示:
(请注意,这是用户参加过的所有活动的第一个也是最后一个(最近的)日期)
+----+-----+---------+----------------------+-----------------------+-----------------------+-----------------------+
| id |name | Event | First date as a host | Recent date as a host | First date as a guest | Recentdate as a guest |
+----+-----+---------+----------------------+-----------------------+-----------------------+-----------------------+
| 1 | Teo | Dance | 2018-01-01 | 2017-01-01 | 2016-02-01 | 2017-09-09 |
| 2 | Jac | Karaoke | 2018-03-02 | 2018-01-01 | 2016-07-07 | 2017-01-06 |
| 3 | Lay | Boxing | 2017-09-09 | 2018-07-07 | 2017-01-01 | 2018-02-02 |
+----+-----+---------+----------------------+-----------------------+-----------------------+-----------------------+
表
用户
ID
名称
事件
ID
命名
starts_at
Event_Users
ID
USER_ID
EVENT_ID
作用
我试着遵循这里的指令[https://www.periscopedata.com/blog/4-ways-to-join-only-the-first-row-in-sql] ...但是当谈到编写一个检索4个不同的第一行(最小/最大)的查询时,我总是得到一个超级凌乱的查询甚至不工作......
对于这种棘手的要求,最简单的解决方案是什么?
由于
答案 0 :(得分:1)
这与need to return two sets of data with two different where clauses的模式相同,只是它使用MIN
和MAX
代替SUM
。
SELECT u.id, u.name, e.name AS Event,
MIN(IF(eu.role = 'host', e.starts_at, NULL)) AS First_date_as_host,
MAX(IF(eu.role = 'host', e.starts_at, NULL)) AS Recent_date_as_host,
MIN(IF(eu.role = 'guest', e.starts_at, NULL)) AS First_date_as_guest,
MAX(IF(eu.role = 'guest', e.starts_at, NULL)) AS Recent_date_as_guest
FROM users AS u
JOIN event_users AS eu ON eu.user_id = u.id
JOIN events AS e ON e.id = eu.event_id
GROUP BY u.id, e.id