MYSQL 随机获取 2 辆汽车,所有颜色(左连接)
我有一个表、Cars
CarID | Car
1 Taurus
2 Ranger
3 Charger
和 CarColors,其中包含每辆车的颜色。
ColorID | CarID | Color
1 1 White
2 1 Blue
3 2 Black
4 1 Red
5 2 Pink
6 3 Orange
我想随机购买两辆车,以及这些车的所有颜色。我尝试过
SELECT * FROM Cars C
LEFT JOIN CarColors CC ON C.CarID = CC.CarID
ORDER BY RAND()
LIMIT 2
但是,可以理解的是,这会返回两行。
我尝试了一个子查询,例如
SELECT * FROM Cars C
LEFT JOIN CarColors CC ON C.CarID = CC.CarID
WHERE C.CarID IN (SELECT CarID FROM Cars
ORDER BY RAND()
LIMIT 2)
But MYSQL does not support LIMIT inside subqueries。
当我尝试搜索此内容时,我得到了限制 JOIN 结果的答案(例如每辆车有一种颜色)
I have a table, Cars,
CarID | Car
1 Taurus
2 Ranger
3 Charger
and CarColors with colors for each car.
ColorID | CarID | Color
1 1 White
2 1 Blue
3 2 Black
4 1 Red
5 2 Pink
6 3 Orange
I want to get a random two cars, and all colors for those cars. I tried
SELECT * FROM Cars C
LEFT JOIN CarColors CC ON C.CarID = CC.CarID
ORDER BY RAND()
LIMIT 2
But this, understandably, returns two rows.
I tried a subquery, something like
SELECT * FROM Cars C
LEFT JOIN CarColors CC ON C.CarID = CC.CarID
WHERE C.CarID IN (SELECT CarID FROM Cars
ORDER BY RAND()
LIMIT 2)
But MYSQL doesn't support LIMIT within subqueries.
When I try to search for this, I get answers for limiting the JOIN's results (like 1 color for each car)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的MySQL版本支持
ROW_NUMBER
窗口函数,您可以尝试这个sqlfiddle
另一种方法是您可以使用子查询来获取随机汽车,然后执行
加入
If your MySQL version support
ROW_NUMBER
window function, you can try thissqlfiddle
Another way is you can just use a subquery to get random cars then do
JOIN