MYSQL 随机获得 2 辆汽车,所有颜色(LEFT JOIN)

MYSQL Get random 2 Cars, all colors (LEFT JOIN)

我有一辆table,汽车,

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

但是,可以理解,returns 两行。

我尝试了一个子查询,比如

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)

但是 MYSQL 不支持子查询中的 LIMIT。

当我尝试搜索这个时,我得到了限制 JOIN 结果的答案(比如每辆车 1 种颜色)

如果你的MySQL版本支持ROW_NUMBERwindow功能,你可以试试这个

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

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

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