我只想在单个查询中执行多个表操作。查询是:
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'
当我尝试使用时,此查询无效**总计> 0 **。还有其他可行的方法吗?请帮我。
答案 0 :(得分: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
部分是如何消失的?那是因为如果没有要加入的行,则不会加入任何内容并从结果中删除行;)