怎么写mysql查询对应这个表

时间:2013-10-25 08:37:19

标签: mysql

嗨数据库专业人士。我需要你的帮助

这是我的数据库表

enter image description here

我想得到这个结果

enter image description here

如何编写选择查询以获得该结果?

我写了这个查询,但效果很慢(20分钟)

SELECT  c.name, p.title,  tbl1.count, tbl1.sum,tbl2.count_1, tbl2.sum_1, tbl3.count_2, tbl3.sum_2
FROM `client` c LEFT JOIN        
(SELECT c.name, p.id, p.title,p.unit,  o.client_id,  COUNT(*) AS `count`, SUM(op.price) AS `sum`
 FROM `order` o INNER JOIN order_product op ON o.id = op.order_id
        INNER JOIN product p ON op.product_id = p.id    
        INNER JOIN `client` c ON c.id = o.client_id
  WHERE MONTH(o.date) = MONTH('2013-07-01') AND YEAR(o.date) = YEAR('2013-07-01') AND p.category_id = 1
 GROUP BY c.id, p.id,  YEAR(o.date), MONTH(o.date)) AS tbl1 ON c.id = tbl1.client_id 
LEFT JOIN 
(SELECT p.id, p.title,p.unit, c.name, o.client_id, COUNT(*) AS `count_1`, SUM(op.price) AS `sum_1`
        FROM `order` o INNER JOIN order_product op ON o.id = op.order_id
        INNER JOIN product p ON op.product_id = p.id
        INNER JOIN `client` c ON c.id = o.client_id
        WHERE MONTH(o.date) = MONTH(DATE_ADD('2013-07-01', INTERVAL 1 MONTH)) AND 
                YEAR(o.date) = YEAR(DATE_ADD('2013-07-01', INTERVAL 1 MONTH))   AND p.category_id = 1                           
        GROUP BY c.id, p.id,  YEAR(o.date), MONTH(o.date)) AS tbl2 ON c.id = tbl2.client_id
LEFT JOIN           
(SELECT p.id, p.title,p.unit, c.name, o.client_id, COUNT(*) AS `count_2`, SUM(op.price) AS `sum_2`
        FROM `order` o INNER JOIN order_product op ON o.id = op.order_id
        INNER JOIN product p ON op.product_id = p.id    
        INNER JOIN `client` c ON c.id = o.client_id 
        WHERE MONTH(o.date) = MONTH(DATE_ADD('2013-07-01', INTERVAL 2 MONTH)) AND 
                YEAR(o.date) = YEAR(DATE_ADD('2013-07-01', INTERVAL 2 MONTH))   AND p.category_id = 1           
        GROUP BY c.id, p.id,  YEAR(o.date), MONTH(o.date)) AS tbl3 ON c.id = tbl3.client_id
        , product p
WHERE (tbl1.id = p.id OR tbl2.id = p.id OR tbl3.id = p.id)

ORDER BY c.name

0 个答案:

没有答案