为什么这一切都不起作用?请解释

时间:2014-03-03 10:21:17

标签: sql

“=”之前的第一部分正在工作,“=”之后的第二部分也正常工作,结果需要为1300.所以为什么这一切都不起作用?请解释

SELECT c.c_id, c.c_name, SUM( p.p_sum ) AS sum
FROM clients c, contracts_rent r, payments p
WHERE c.c_id = r.c_id
AND r.contract_id = p.contract_id
GROUP BY c.c_id
HAVING SUM( p.p_sum ) =SELECT MAX( temp.sum ) 
FROM ( SELECT r.c_id AS Cman, SUM( p.p_sum ) AS sum
       FROM contracts_rent r, payments p
       WHERE r.contract_id = p.contract_id
       GROUP BY r.c_id
     ) AS temp

1 个答案:

答案 0 :(得分:0)

SELECT c.c_id, c.c_name, SUM( p.p_sum ) AS my_sum
FROM clients c, contracts_rent r, payments p
WHERE c.c_id = r.c_id
AND r.contract_id = p.contract_id
GROUP BY c.c_id, c.c_name
ORDER BY my_sum DESC 
LIMIT 1

理论上,如果你添加一些parantheses你的解决方案是有效的:

SELECT c.c_id, c.c_name, SUM( p.p_sum ) AS sum
FROM clients c, contracts_rent r, payments p
WHERE c.c_id = r.c_id
AND r.contract_id = p.contract_id
GROUP BY c.c_id
HAVING SUM( p.p_sum ) = (SELECT MAX( temp.sum ) 
FROM ( SELECT r.c_id AS Cman, SUM( p.p_sum ) AS sum
       FROM contracts_rent r, payments p
       WHERE r.contract_id = p.contract_id
       GROUP BY r.c_id
     ) AS temp
)

解决方案之间的区别在于,第一个只产生一行,无论是否有两行或更多行具有相同的p.p_sum总和。第二个将产生所有max(sums)