无法将两个查询合并为一个

时间:2014-06-07 05:33:07

标签: mysql sql

我想获取所有customer_details将所有字段和帐单总数以及customer_details(id,name,address,...)bill_details(bill_no,customer_id,price,...)表中存储的帐单金额总和。

获取两者的基本查询首先是:

select  cd.* from customer_details as cd

然后这个:

select customer_id,count(*) as billCount,sum(total) price from bill_details group by customer_id;

我无法在一个查询中将这两者结合起来,以使用帐单金额和计数来获取所有客户详细信息。

3 个答案:

答案 0 :(得分:0)

尝试使用JOIN

SELECT cd.*,IFNULL(T.billCount,0) as billCount,IFNULL(T.price,0) as price
FROM customer_details as cd LEFT JOIN
(SELECT customer_id,count(*) as billCount,sum(total) price 
 FROM bill_details 
 GROUP BY customer_id) T ON cd.id=T.customer_id

答案 1 :(得分:0)

我试过以下去正确的结果我可以使用这个

select  cd.*,IFNULL(count(*),0) as count,IFNULL(sum(bd.total),0) as total from customer_details as cd
left join bill_details as bd
on cd.id=bd.customer_id
group by cd.id;

答案 2 :(得分:0)

SELECT cd.id,
       cd.nmae, 
       cd.address
       IFNULLCOUNT(bd.*),0) AS billcount, 
       IFNULL(SUM(bd.price * bd.quantity),0) as total /* I suppose you have a quantity field in bd */
FROM customer_details cd
LEFT JOIN bill_details bd
ON cd.id = bd.customer_id
GROUP BY cd.id, 
         cd.nmae, 
         cd.address