Home  >  Article  >  Backend Development  >  问一个关于MYSQL链表的问题

问一个关于MYSQL链表的问题

WBOY
WBOYOriginal
2016-06-23 13:42:11734browse

a1 

a2

a3


三个表现在我的写法是 
select a1.*,sum(a2.money) as money from a1 left join a2 on a1.id=a2.id left join a3 on a2.no = a3.no group by a1.id ;
得出的结果是


出于其它因素必须要连接a3表,导致了money为35,我想要的是money为25,应该怎么写?


回复讨论(解决方案)

a3.no 不唯一,导致 a2.no=a3.no 时 a2 的 (11 1 10.00)出现两次
所以你需对 a3 加约束条件
 

a3.no 不唯一,导致 a2.no=a3.no 时 a2 的 (11 1 10.00)出现两次
所以你需对 a3 加约束条件
 


是的呀,我以为有什么办法可以解决,看来不能这样链表查了。。
如果写成 
select a1.name,  
(select sum(count) from a3 where no in (select no from a2 where id = a1.id )) as count ,
sum(a2.money) as money 
from a1 left join a2 on a1.id=a2.id  group by a1.id ;
的结果为 

但我想要 money 减去 count 的值应该怎么写呢
25-400
20-200
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP中Memcache类函数详解Next article:无状态点赞功能