我有2张桌子:
Table1:
ID | Mobile Number | Name | Ordered Product| Order Date
表2:
ID(foreign_key can be inserted multipletimes in this table) |Contacted_for | Time(timestamp)
我需要一个查询来显示Table1中的所有数据,如果表2中有ID,我需要显示该ID的Table2(随时间)的最后插入记录
我的疑问是
select a.* , b.* FROM table1 a LEFT JOIN table2 b ON a.ID=b.ID GROUP BY a.ID ORDER BY b.Time DESC
在我的查询中,当我删除Group by a.ID时,它可以工作但显示所有结果.但我想只显示table2的最终记录(没有重复的ID记录)
提前致谢
解决方法:
你需要一些子查询:
SELECT
a.*, b.*
FROM
table1 a
LEFT JOIN
(SELECT c.id, d.contacted_for, c.time
FROM
(SELECT
id,
MAX(time) time
FROM
table2
GROUP BY id
) c
JOIN
table2 d
ON c.id = d.id AND d.time = c.time
) b
ON a.id = b.id
标签:php,mysql
来源: https://codeday.me/bug/20190609/1206206.html