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

MYSQL select 3 random records where at least one record-field has certain value

我正在尝试从 table 中 select 3 个随机记录,前提是结果应至少包含一个值 'number' 大于 3 的记录。

示例table:

+--------+-------+--------+
| 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.

我试过了,但它无法 return 结果总是至少包含一个值大于 3 的记录:

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

我想我走错了路.. 任何帮助将不胜感激!

使用 CTE 创建所有可能的组合 select 从使用交叉连接:

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