以下查询不起作用:
(
SELECT *
FROM `items`
WHERE `name` LIKE '%SCAR%' AND `rarity` = 'Legendary'
ORDER BY weight / RAND( ) DESC
LIMIT 0, 1
)
UNION
(
SELECT *
FROM `items`
WHERE `rarity` = 'Legendary'
ORDER BY weight / RAND( ) DESC
LIMIT 0, 3
)
UNION
(
SELECT *
FROM `items`
WHERE `rarity` = 'Epic'
ORDER BY weight / RAND( ) DESC
LIMIT 0, 1
)
GROUP BY
weight
HAVING
SUM(value) < 100
ORDER BY
RAND()
然而,这单独起作用:
(
SELECT *
FROM `items`
WHERE `name` LIKE '%SCAR%' AND `rarity` = 'Legendary'
ORDER BY weight / RAND( ) DESC
LIMIT 0, 1
)
UNION
(
SELECT *
FROM `items`
WHERE `rarity` = 'Legendary'
ORDER BY weight / RAND( ) DESC
LIMIT 0, 3
)
UNION
(
SELECT *
FROM `items`
WHERE `rarity` = 'Epic'
ORDER BY weight / RAND( ) DESC
LIMIT 0, 1
)
ORDER BY RAND()
我如何添加条件,即从数据库中选择的所有行的值字段之和至少为设定值(例如1000)?感谢
答案 0 :(得分:1)
SELECT stuff
FROM (unions) AS u
GROUP BY u.somefield
HAVING SUM(u.anotherfield) < somevalue
;
使工会成为子查询。但请注意,选择非聚合的非分组字段通常是不受欢迎的,除了MySQL以外的所有字段都不允许(甚至它的最新版本的默认配置也不允许),对于这种查询可能是一个非常糟糕的想法。
此外,RAND()
并不总是按照您的想法行事。在你的UNIONed查询中,你可能会将每个权重除以不同的RAND()值(因为必须对每个权重进行评估);但是你的最终ORDER BY RAND()
可以使用相同的单个RAND()值排序所有结果,因为mysql可能需要一个快捷方式并且只评估一次。