加入三个mysql表,包括where子句中的条件

时间:2014-07-28 16:35:49

标签: php mysql join

我对mysql表加入知之甚少,所以我无法解决以下问题。我有以下三个表

  member table 

name           country
-----         --------
adam          bangladesh  

smith         england 

jon           United states

geric         bangladesh  

romio         england 

jelon         United states


table order

order_amount     country       approved 
-----        --------      -------
20            bangladesh      1

25            england         0

20            United states   1  

40            bangladesh      1

20            england         1

40            United states   0


table withdraw

withdraw_amount   country
--------------   --------
2                bangladesh  

4                england 

6                United states

8                bangladesh  

10               england 

22               United states  


my desired table


country_name   total_member  total order total paid                     
------------   ------------  ---------   ----------

bangladesh         2         60        10

england            2         20        14

United states      2         20        28

我想更详细地解释一下,从成员表中我想获得分组的国家/地区数据,以便我可以告诉特定国家/地区有多少成员。

从订单表中我想获得批准的order_amount的总和等于1.这意味着我试图列出来自特定国家/地区的总批准订单金额

从表格提取中我想总结withdraw_amount,以便我可以知道特定国家/地区的提款总额。

最后,我想要的表格将包含国家名称及其相应的total_member,总订单,总付费金额。任何人都可以告诉我这个难以加入的查询?

1 个答案:

答案 0 :(得分:0)

这就是你想要的。使用左连接匹配3个查询

select * from (select country as country_name, count(name) as total_member  from members m
group by country) members left join 
(select sum(ammount) as total_order , country from orders where aproved = 1 group by country) ammounts on country_name = ammounts.country
left join
(select sum(withraw) as total_paid , country from withraw group by country) withraw on country_name = withraw.country

see it in action here