为什么我的SQL语句有时不返回结果?

时间:2018-12-03 09:47:58

标签: mysql sql

给出下表:

enter image description here

我们有以下返回随机行的SQL语句:

SELECT r1.id, game_desc, rarity, unlocks_prior 
FROM items_permanent AS r1 
JOIN (
    SELECT (RAND() * (SELECT MAX(id) FROM items_permanent)) AS id
) AS r2    
WHERE r1.id >= r2.id AND r1.unlocks_prior is Null 
ORDER BY r1.id ASC 
LIMIT 1

这可以正常工作,但是当我们需要根据稀有性进行随机分组时,需要将以上内容更改为以下内容:

SELECT r1.id, game_desc, rarity, unlocks_prior 
FROM items_permanent AS r1 
JOIN (
    SELECT (RAND() * (SELECT MAX(id) FROM items_permanent)) AS id
) AS r2 
WHERE r1.id >= r2.id AND r1.unlocks_prior is Null AND r1.rarity = ? 
ORDER BY r1.id ASC 
LIMIT 1

它有时根本不返回任何行,而且具有令人震惊的规律性(我说十分之一的执行)。

是什么原因造成的?我该如何预防或修复它?

2 个答案:

答案 0 :(得分:2)

您的查询正在选择ID范围内的随机数,然后在表中查找与条件匹配的下一行。如果随机ID之后的所有行均不符合条件,则您将一无所获。选择随机ID时还需要包括条件。

SELECT r1.id, game_desc, rarity, unlocks_prior 
FROM items_permanent AS r1 
JOIN (
    SELECT RAND() * MAX(id) AS id
    FROM items_permanent
    WHERE unlocks_prior is Null AND rarity = ? 
) AS r2 ON r1.id >= r2.id
WHERE r1.unlocks_prior is Null AND r1.rarity = ? 
ORDER BY r1.id ASC 
LIMIT 1

答案 1 :(得分:1)

我看到的是您在下面的第二条SQL中添加了

AND r1.rarity = ? 

以图像中显示的数据为例,假设您的ID为1〜29,如果r1.rarity = 2且r2.id滚动为28,您将一无所获(coz no rarity = 2且ID 28- 29)

应该可以通过更改以下声明来解决

SELECT (RAND() * (SELECT MAX(id) FROM items_permanent)) AS id

进入

SELECT (RAND() * (SELECT MAX(id) FROM items_permanent WHERE rarity = ?)) AS id