如何使用Join而不是子查询进行以下查询?

时间:2015-12-12 17:34:44

标签: php mysql join subquery

问候语, 正如许多帖子所见,子查询比加入慢...

但是我找不到使用任何连接方法进行后续查询的方法..所以,我使用了子查询。

任何人都可以告诉我如何在以下情况下正确使用连接:

表1:

customerID, Name
1, abc
2, xyz
3, qwe
4, zxc
5, asd
and so on

表2:

customerID, Month, OrderNumbers
1, jan, 5
1, feb, 6
2, jan, 8
3, feb, 5
4, mar, 3
and so on..

我需要像这样报告:

customer id, name, jan order, feb order, mar order
1, abc, 5, 6, 0
2. xyz, 8, 0, 0
3. qwe, 0, 5, 0
and so on

我正在使用此查询:

select table1.customerID,
       table1.Name,
       (select table2.Month as jan
         where table2.Month = jan),
       (select table2.Month as feb
         where table2.Month = feb),
       (select table2.Month as mar
         where table2.Month = mar)
  from table1 

但这不应该正常工作......

所以,我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您的查询基本上需要进行长到宽的整形或数据转换,这可以通过条件聚合完成:

SELECT 
    table1.customerID,
    table1.`name`,      

    SUM(CASE WHEN table2.`Month` = 'jan' THEN table2.`OrderNumbers` END) As 'jan order',
    SUM(CASE WHEN table2.`Month` = 'feb' THEN table2.`OrderNumbers` END) As 'feb order',
    SUM(CASE WHEN table2.`Month` = 'mar' THEN table2.`OrderNumbers` END) As 'mar order',
    SUM(CASE WHEN table2.`Month` = 'apr' THEN table2.`OrderNumbers` END) As 'arp order',
    SUM(CASE WHEN table2.`Month` = 'may' THEN table2.`OrderNumbers` END) As 'may order',
    SUM(CASE WHEN table2.`Month` = 'jun' THEN table2.`OrderNumbers` END) As 'jun order',
    SUM(CASE WHEN table2.`Month` = 'jul' THEN table2.`OrderNumbers` END) As 'jul order',
    SUM(CASE WHEN table2.`Month` = 'aug' THEN table2.`OrderNumbers` END) As 'aug order',   
    SUM(CASE WHEN table2.`Month` = 'sep' THEN table2.`OrderNumbers` END) As 'sep order',
    SUM(CASE WHEN table2.`Month` = 'oct' THEN table2.`OrderNumbers` END) As 'oct order',
    SUM(CASE WHEN table2.`Month` = 'nov' THEN table2.`OrderNumbers` END) As 'nov order',
    SUM(CASE WHEN table2.`Month` = 'dec' THEN table2.`OrderNumbers` END) As 'dec order'

FROM
    table1
LEFT OUTER JOIN 
    tabl2 ON table1.customerID = table2.customerID
GROUP BY 
    table1.customerID,
    table1.`name`

答案 1 :(得分:0)

这是我在msql中多次使用过的解决方案......

select customerID,Name,sum(jan) as jan,sum(feb) as feb from(
select table1.customerID,Name,(case when Month = 'jan' then OrderNumbers else 0 end) as jan, select table1.customerID,Name,(case when Month = 'feb' then OrderNumbers else 0 end) as febfrom table1
left join table2 on table2.customerID = table1.customerID
) as src group by customerID,Name

基本上你使用一个精选案例来只用sales或0来填充月份,它会给你类似的东西

1,abc,5,0,0
1,abc,0,3,0
2,ddd,0,0,5

然后,您只需将结果分组并将月份相加。