MYSQL选择3条随机记录,其中至少一个记录字段具有特定值

时间:2019-03-18 14:29:42

标签: mysql conditional

我正在尝试从一个表中选择3条随机记录,条件是结果中至少应包含一条'number'值大于3的记录。

示例表:

+--------+-------+--------+
| ID     | name  | number |
+--------+-------+--------+
| 1      | name1 | 5      |
+--------+-------+--------+
| 2      | name2 | 0      |
+--------+-------+--------+
| 3      | name3 | 2      |
+--------+-------+--------+
| 4      | name4 | 7      |
+--------+-------+--------+
| 5      | name5 | 9      |
+--------+-------+--------+
| 6      | name6 | 1      |
+--------+-------+--------+
| etc... |       |        |
+--------+-------+--------+

因此,结果可能是ID为:1,2和6或1,4和9的记录,但不是2,3和6的记录,因为该结果不包含至少一个'number'> 3的记录。

我尝试了此操作,但是它无法返回始终包含至少一个记录的值> 3的结果:

SELECT name, number  FROM   table
WHERE  EXISTS (
   SELECT number FROM table
   WHERE  number > 3
   ) 
ORDER BY RAND()
LIMIT 3

我认为我走错了路。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

使用CTE通过交叉连接创建所有可能的组合以供选择:

WITH cte AS (
  SELECT 
    n1.id id1, n1.name name1, n1.number number1,
    n2.id id2, n2.name name2, n2.number number2,
    n3.id id3, n3.name name3, n3.number number3
  FROM numbers n1 CROSS JOIN numbers n2 CROSS JOIN numbers n3
  WHERE 
    (n1.number > 3 OR n2.number > 3 OR n3.number > 3)
    AND n1.id <> n2.id AND n1.id <> n3.id AND n3.id <> n2.id
  ORDER BY RAND() LIMIT 1
)

SELECT id1 id, name1 name, number1 number FROM cte
UNION ALL
SELECT id2 id, name2 name, number2 number FROM cte
UNION ALL
SELECT id3 id, name3 name, number3 number FROM cte

请参见demo