从三个表中选择查询

时间:2011-01-20 10:42:37

标签: mysql sql

我有表格客户,广告系列,交易和事实2.我写了一个像下面这样的查询来显示

SELECT id,
(select customer.name from customer where customer.id = facts2.customer_id) 
  AS Customername,
(select campaign.name from campaign where campaign.id = facts2.campaign_id) 
  AS Campaignname,
(select deal.name from jb_deal where deal.id = facts2.deal_id) 
  AS Dealname,
revenue 
from facts2; 
    +--------------+-------------+-------------------+----------+
    | Customername | Campaignanme |  Dealname         |  revenue |
    +-------------+-------------+-------------------------------+
    |           A |       Camp1 |               Deal1 |   100  |
    |           A |       Camp1 |               Deal2 |   200  | 
    |           A |       Camp2 |               Deal3 |   300  |
    |           B |       CampB |              DealB1 |   100  |
    |           B |       CampB |              DealB2 |   200  |
    |           C |       CampC |               Deal3 |   300  |
    +-------------+-------------+--------------------------------+

我想显示sql表而不重复客户名称和广告系列名称,如下所示。

    +--------------+-------------+-------------------+----------+
    | customername | campaignanme | dealname         |  Revenue |
    +-------------+-------------+-------------------------------+
    |           A |       Camp1 |               Deal1 |   100  |
    |             |             |               Deal2 |   200  | 
    |             |       Camp2 |               Deal3 |   300  |
    |           B |       CampB |              DealB1 |   100  |
    |             |             |              DealB2 |   200  |
    |           C |       CampC |               Deal3 |   300  |
    +-------------+-------------+--------------------------------+

1 个答案:

答案 0 :(得分:0)

你不能这样做仍然可以使用UNION来获取不同的条目。 如果你想要你可以这样做

SELECT `result`.`Customername`,`result`.`Campaignname`,
GROUP_CONCAT(`result`.`Dealname`) AS `Dealname`,SUM(`revenue`) AS `revenue` FROM (SELECT id,
(select customer.name from customer where customer.id = facts2.customer_id) 
  AS Customername,
(select campaign.name from campaign where campaign.id = facts2.campaign_id) 
  AS Campaignname,
(select deal.name from jb_deal where deal.id = facts2.deal_id) 
  AS Dealname,
revenue 
from facts2) AS `result` GROUP BY `result`.`Campaignname`,`result`.`Customername`; 

结果将是这样的

+--------------+-------------+-------------------+----------+
| Customername | Campaignanme |  Dealname        |  revenue |
+-------------+-------------+-------------------------------+
|           A |       Camp1 |         Deal1,Deal2 |   300  |
|           A |       Camp2 |               Deal3 |   300  |
|           B |       CampB |       DealB1,DealB2 |   300  |
|           C |       CampC |               Deal3 |   300  |
+-------------+-------------+--------------------------------+