1

我只想在单个查询中执行多个表操作。查询是:

    select name,sno , id  as ids ,(select sum(amount) from client_credits 
where user_id = ids) As total  from clients where sno = '4' and total > '0'

当我尝试使用 ** total > 0 ** 时,此查询不起作用。还有其他可能的方法吗?请帮我。

4

1 回答 1

2

total是别名。WHERE到达该子句时不会解析别名。

尝试:where sno = 4 having total > 0

或者,更有效地:

SELECT `c`.`name`, `c`.`sno`, `c`.`id`, SUM(`ccr`.`amount`) AS `total`
FROM `clients` AS `c`
JOIN `client_credits` AS `ccr` ON `c`.`id`=`ccr`.`user_id`
WHERE `c`.`sno` = 4
GROUP BY `c`.`id`

注意total > 0零件是如何消失的?那是因为如果没有要加入的行,则不会加入任何内容,并且会从结果中删除行;)

于 2014-06-24T07:54:46.627 回答