我有两张这样的表 - >
Categories
-----------
id name
---------
1 --> a
2 --> b
3 --> c
Messages
------------
id catid message
---------------------------
1 --> 1 --> aa
2 --> 1 --> bb
3 --> 1 --> cc
4 --> 2 --> dd
5 --> 3 --> ee
6 --> 3 --> ff
i want to join the tables for get FIRST message from messages table,
我想要这样的查询结果 - >
-------------------------------
id name message
1 a aa
2 b dd
3 c ee
我找到了一个代码
select * from categories c, items i
-> where i.categoryid = c.id
-> group by c.id;
但没有任何ORDER BY程序
答案 0 :(得分:1)
SELECT c.*, i.*
FROM categories c
JOIN items i ON (i.categoryid = c.id)
LEFT OUTER JOIN items i2 ON (i2.categoryid = c.id
AND (i.message > i2.message OR i.message = i2.message AND i.id > i2.id))
WHERE i2.categoryid IS NULL
ORDER BY c.id;
这往往在MySQL上表现更好,因为MySQL在GROUP BY
查询时表现得非常糟糕。
答案 1 :(得分:0)
如果按第一个分组,MySql将始终返回第二个表中的第一个记录。
SELECT a.id, a.name, b.message FROM Categories a, Messages b WHERE b.catid = a.id GROUP BY a.id ORDER BY a.id