说我有两张桌子要加入。 分类:
id name
----------
1 Cars
2 Games
3 Pencils
4 Books
和项目:
id categoryid itemname
---------------------------
1 1 Ford
2 1 BMW
3 1 VW
4 2 Tetris
5 2 Pong
6 3 Foobar Pencil Factory
我想要一个返回类别和最后一个最大N(例如:2)itemname:
的查询category.id category.name item.id item.itemname
-------------------------------------------------
1 Cars 2 BMW
1 Cars 3 VW
2 Games 4 Tetris
2 Games 5 Pong
3 Pencils 6 Foobar Pencil Factory
4 Books NULL NULL
我想写一个如下的查询:
Select * From categories c
Left Join (select * from items order by id desc) i
On c.id=i=categoryid
AND LIMIT 2 #comment: N=2 this line not supported
Where i.categoryid = c.id
Group By c.id
谢谢!
答案 0 :(得分:4)
我不是说效率很高,但应该有效:
SELECT c.*, i.id, i.itemname
FROM categories c
LEFT JOIN
(SELECT i.*
FROM items i
LEFT JOIN items i2 ON i.categoryid = i2.categoryid AND i2.id > i.id
GROUP BY i.id
HAVING COUNT(*) < 2 # this 2 = N
) i ON c.id = i.categoryid
答案 1 :(得分:2)
检查http://sqlfiddle.com/#!2/9a132/1
SELECT *
FROM Categories c
LEFT JOIN -- Items i
(
SELECT * FROM Items WHERE LOCATE(id,
(
SELECT GROUP_CONCAT(it.itemids) AS its
FROM (
SELECT (SUBSTRING_INDEX(GROUP_CONCAT(CONVERT(id, CHAR(8))
ORDER BY id DESC), ',', 2)) AS itemids
FROM Items
GROUP BY categoryid
) it
)) <> 0
) i
ON i.categoryid = c.id;
其中N = 2是:SUBSTRING_INDEX(GROUP_CONCAT(CONVERT(id,CHAR(8))ORDER BY id DESC),',',2)
因为GROUP_CONCAT默认排序为ASC;上面将成为SUBSTRING_INDEX(GROUP_CONCAT(CONVERT(id,CHAR(8))),',', - 2)。但GROUP_CONCAT结果被截断为max len 1024(group_concat_max_len)。