我有两张桌子
table1: { id, name }
table2: { id, table1_id, time_added }
可以在一个查询中只获取表2中所有项目中最后添加的相关项目吗?
答案 0 :(得分:2)
这将有效:
SELECT
t1.*,
t2.*
FROM Table1 t1
INNER JOIN table2 t2 on t2.table1_id = t1.id
INNER JOIN (SELECT Max(time_added) as time_added, table1_id FROM Table2 Group by table1_id) t2a on
t2a.time_added = t2.time_added AND t2a.table1_id = t2.table1_id
答案 1 :(得分:0)
SELECT table1.id,table1.name FROM table1 JOIN table2 ON table1.id = table2.id GROUP BY table2.id ORDER BY time_added DESC;
这是你的答案,如果你需要澄清,请告诉我。
答案 2 :(得分:0)
选择表2中最后添加的项目非常简单。
SELECT * FROM TABLE1 AS tb1 WHERE tb1.id IN (SELECT MAX(id) FROM TABLE2)
注意:在上面的查询中,table1的id和table2的id必须是AUTO INCREMENTED。
尝试以上查询。
谢谢!
答案 3 :(得分:0)
使用此解决方案,您不需要子查询... 基于ajacian81
SELECT table1.*, table2.*
FROM table1 LEFT JOIN table2
ON table1.id = table2.table1_id
GROUP BY table1.id
ORDER BY table2.time_added DESC;