我的数据库中有以下表格:
用户
+-------+-------------------------------------+
| id | name |
+-------+-------------------------------------+
| 1 | Johnny Appleseed |
| 2 | Pete Jones |
| 3 | John Doe |
| 4 | Jane Plick |
+-------+-------------------------------------+
报告
+-------+-------+-----------------------------+
| id | owner | title |
+-------+-------+-----------------------------+
| 1 | 1 | Weekly report #86 |
| 2 | 1 | Weekly report #87 |
| 3 | 1 | Weekly report #88 |
| 4 | 2 | Weekly report #1 |
| 5 | 3 | Weekly report #33 |
| 6 | 3 | Weekly report #34 |
+-------+-------------------------------------+
我需要做的是按名字对结果进行分组,以便列表本身按字母顺序排列,但我需要最后一次出现与用户ID相匹配的行。
REPORTS表的“owner”列与USERS表的“id”列匹配。
我想要的结果如下:
Jane Plick |
John Doe | Weekly Report #34
Johnny Appleseed | Weekly Report #88
Pete Jones | Weekly Report #1
我当前的查询ALMOST有效,但它只显示该用户的第一周报告,而不是最后一次。
SELECT * FROM users AS a LEFT JOIN ppp_reports AS b ON a.id=b.owner WHERE a.active=1 GROUP BY a.id ORDER BY a.firstname ASC
我尝试了很多不同的变体,但我总是留在REPORTS表中的第一行。
非常感谢任何帮助。
答案 0 :(得分:0)
在您的特定情况下,所有报告都被命名为"每周报告#X",您可以尝试这样做:
SELECT a.id, a.name, MAX(b.title)
FROM users AS a
LEFT JOIN ppp_reports AS b ON a.id=b.owner
WHERE a.active=1
GROUP BY a.id, a.name
ORDER BY a.name ASC
请参阅this fiddle。
如果报告可能有其他名称,您必须找到另一种方法来区分上次报告与其他报告。
答案 1 :(得分:0)
假设您的报告ID按日期编号,即报告ID 2始终在报告ID 1之后,这两个查询应该有效:
select t.id, t.name, r.title from
(select u.id, u.name, max(r.id) as report_id
from users u
left join reports r on r.owner = u.id
group by u.id, u.name) as t
left join reports r on t.report_id = r.id;
OR
select u.id, u.name, r.title from
users u
left join
(select r.owner, max(r.id) as report_id
from reports r
group by r.owner) as latest_report on u.id = latest_report.owner
left join reports r on latest_report.report_id = r.id;
您的想法是,您需要按用户ID识别正确的报告,然后将报告表连接回来,以获取报告的正确名称。