gpt4 book ai didi

mysql - 加入右表限制

转载 作者:行者123 更新时间:2023-11-29 01:22:32 24 4
gpt4 key购买 nike

假设我有两个要加入的表。分类:

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)项名称的查询:

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

谢谢!

最佳答案

我并不是说它很有效,但它应该有效:

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

关于mysql - 加入右表限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com