如何在MySQL中结合使用Rand功能

时间:2014-03-27 23:09:51

标签: mysql sql select

我正在尝试合并3个选择语句的结果,这些语句将从不同的食物类别中选择不同的食物名称。然而,我的桌子很少有“foodItems”的例子。我需要为每个select语句只选择1个项目,我希望它是随机完成的。我不太确定如何实现我已经尝试在每个select语句的末尾插入ORDER BY RAND() LIMIT 1但MySQL不喜欢它。有人可以提供帮助

SELECT foodName
FROM food
WHERE foodCategory_id = 1 OR 2
UNION
SELECT foodName
FROM food
WHERE foodCategory_id = 7 OR 8 OR 9
UNION
SELECT foodName
FROM food
WHERE foodCategory_id = 10 OR 11

2 个答案:

答案 0 :(得分:0)

SELECT foodname FROM food WHERE .. ORDER BY RAND() LIMIT 0,1;

只需添加您想要的任何条件。

答案 1 :(得分:0)

您可以创建一个外部SQL,其中from子句是某种临时表,如下所示:

 SELECT food_name from (
  SELECT foodName
  FROM food
  WHERE foodCategory_id = 1 OR 2
  ORDER BY RAND() limit 1) a
 UNION
 SELECT food_name from (
  SELECT foodName
  FROM food
  WHERE foodCategory_id = 7 OR 8 OR 9
  ORDER BY RAND() limit 1) b
 UNION
 SELECT food_name from (
  SELECT foodName
  FROM food
  WHERE foodCategory_id = 10 OR 11
  ORDER BY RAND() limit 1) c