我的查询效果很好:
SELECT dl.*, d.*, dr.earn_rate
FROM list dl LEFT JOIN rates dr ON dr.id=dl.id AND dr.level = dl.level
LEFT JOIN widgets d ON d.id=dl.id WHERE user_id=1 AND d.element=3
ORDER BY dr.earn_rate DESC, dl.name LIMIT 20;
我想快速获得所有earn_rate的SUM,并且认为我可以将SUM放入SELECT中,并保留其他所有内容,它会起作用。但是,它似乎忽略了LIMIT并将所有的赚钱额加起来,好像没有限制一样。
SELECT SUM(dr.earn_rate) FROM list dl
LEFT JOIN rates dr ON dr.id=dl.id AND dr.level = dl.level
LEFT JOIN widgets d ON d.id=dl.id WHERE user_id=1 AND d.element=3
ORDER BY dr.earn_rate DESC, dl.name LIMIT 20;
答案 0 :(得分:2)
LIMIT
子句应用于结果集,而不是用于形成结果的中间结果。如果您想将前20个收入相加,则需要使用子查询:
SELECT SUM(earn_rate)
FROM (
SELECT dr.earn_rate
FROM list dl
LEFT JOIN rates dr ON dr.id=dl.id
AND dr.level = dl.level
LEFT JOIN widgets d ON d.id=dl.id
WHERE user_id=1
AND d.element=3
ORDER BY dr.earn_rate DESC, dl.name
LIMIT 20) x