如何修复不一致的 mysql 结果?

How to fix inconsistent mysql results?

我的MySQL查询

(SELECT * FROM names WHERE Rate = 75 ORDER BY RAND() LIMIT 1) 
UNION 
(SELECT * FROM names WHERE Rate = 75 ORDER BY RAND() LIMIT 1) 
UNION 
(SELECT * FROM names  WHERE Rate = 35 ORDER BY RAND() LIMIT 1);

它应该给我这样的东西

+----+-----+------+
| id | Rate| num  |
+----+-----+------+
| id |  75 |  987 |
| id |  75 |  987 |
| id |  35 |  987 |
+- --+-----+------+

但有时它只给我 2 行,像这样

+----+-----+------+
| id | Rate| num  |
+----+-----+------+
| id |  75 |  987 |
| id |  35 |  987 |
+- --+-----+------+

注意UNIONUNION ALL

的区别
  • UNION 将删除重复的行
  • UNION ALL 保留所有行

UNION 删除重复行。

前 2 个查询可能 return 同一行,在这种情况下,其中一个只会出现在结果中。

如果您不介意结果中出现重复行,则更改为 UNION ALL:

(SELECT * FROM names WHERE Rate = 75 ORDER BY RAND() LIMIT 1) 
UNION ALL 
(SELECT * FROM names WHERE Rate = 75 ORDER BY RAND() LIMIT 1) 
UNION ALL
(SELECT * FROM names WHERE Rate = 35 ORDER BY RAND() LIMIT 1);

如果您想要唯一行,则使用 LIMIT 2 将前 2 个查询统一为仅 1 个,这样它们 return 2 行:

(SELECT * FROM names WHERE Rate = 75 ORDER BY RAND() LIMIT 2) 
UNION ALL 
(SELECT * FROM names WHERE Rate = 35 ORDER BY RAND() LIMIT 1);

我在这里使用UNION ALL因为它比UNION.

性能更好

要从 table 中获取 3 不同的 行,只需执行以下操作:

SELECT * FROM names WHERE Rate = 35 ORDER BY RAND() LIMIT 3;