MYSQL 随机获取 2 辆汽车,所有颜色(左连接)

发布于 2025-01-11 12:05:25 字数 820 浏览 1 评论 0原文

我有一个表、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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流心雨 2025-01-18 12:05:25

如果您的MySQL版本支持ROW_NUMBER窗口函数,您可以尝试这个

SELECT * FROM 
(
  SELECT *,ROW_NUMBER() OVER(ORDER BY RAND()) rn 
  FROM Cars
) C LEFT JOIN CarColors CC ON C.CarID = CC.CarID
WHERE rn <= 2

sqlfiddle

另一种方法是您可以使用子查询来获取随机汽车,然后执行加入

SELECT * FROM 
(
  SELECT * 
  FROM Cars
  ORDER BY RAND()
  LIMIT 2
) C LEFT JOIN CarColors CC ON C.CarID = CC.CarID

If your MySQL version support ROW_NUMBER window function, you can try this

SELECT * FROM 
(
  SELECT *,ROW_NUMBER() OVER(ORDER BY RAND()) rn 
  FROM Cars
) C LEFT JOIN CarColors CC ON C.CarID = CC.CarID
WHERE rn <= 2

sqlfiddle

Another way is you can just use a subquery to get random cars then do JOIN

SELECT * FROM 
(
  SELECT * 
  FROM Cars
  ORDER BY RAND()
  LIMIT 2
) C LEFT JOIN CarColors CC ON C.CarID = CC.CarID
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文