结合两个具有不同功能的SELECT查询

时间:2019-01-12 18:31:40

标签: mysql sql

我有一张桌子供报告使用。我的首选查询是结合所有销售表

SELECT *, ds_sales.id_sales
FROM ds_sales LEFT JOIN
     ds_payment 
     ON ds_sales.id_sales=ds_payment.id_sales LEFT JOIN 
     customer_info
     ON ds_payment.id_customer=customer_info.id_customer INNER JOIN
     ds_salesdetails
     ON ds_salesdetails.id_sales=ds_sales.id_sales
WHERE customer_info.id_customer = '".$_POST["id_customer"]."'

这是查询的结果

This is the result of the query

我的第二个查询是这样,以过滤相同的销售序列号,因为ds_salesdetails表具有许多销售序列号

select ds_salesdetails.id_sales, count(*),
       group_concat(ds_salesdetails.id_product)
from ds_salesdetails
having count(*) >= 1

我需要合并它们以创建客户销售报告。

1 个答案:

答案 0 :(得分:1)

使用分组的子查询而不是整个表进行连接。

SELECT *, ds_sales.id_sales
FROM ds_sales LEFT JOIN
     ds_payment 
     ON ds_sales.id_sales=ds_payment.id_sales LEFT JOIN 
     customer_info
     ON ds_payment.id_customer=customer_info.id_customer LEFT JOIN
    (SELECT id_sales, count(*) as product_count,
           group_concat(ds_salesdetails.id_product) AS product_list
    from ds_salesdetails
    GROUP BY id_sales) AS grouped ON grouped.id_sales = ds_sales.id_sales
WHERE customer_info.id_customer = '".$_POST["id_customer"]."'