MySQL:查询以获取某些行是必需的

时间:2015-04-28 15:17:44

标签: mysql sql

我需要一个查询,它会给出与某些值相对应的行,无论其值是否为null,或者表中是否存在这些值。

E.g。

SELECT spot_key, market,panel_member, SUM(weight) as TVR 
FROM break_minute_tvr_fixed b 
WHERE b.column1 in (1,3,4,2,3,4) 
  and b.section in (1,2,3,4) 
  and b.sex in (1,2) 
  and b.age in (1,2,3,4,5,6,7) 
  and b.market in ('9')  
  and spot_key in ( '1:20141017:2129' )  
GROUP BY spot_key, market;

这会将行返回为:

+-----------------+--------+---------------------+--------------------+
| spot_key        | market | panel_member        | TVR                |
+-----------------+--------+---------------------+--------------------+
| 1:20141017:2129 | 9      | 010583010102;7.2930 | 134.65280079841614 |
+-----------------+--------+---------------------+--------------------+
1 row in set (0.00 sec)

现在,如果我将另一个值添加到市场列表中,比如表300本身不存在,那么我的查询将成为:

SELECT spot_key, market,panel_member, SUM(weight) as TVR 
  FROM break_minute_tvr_fixed b 
 WHERE b.column1 in (1,3,4,2,3,4) 
   and b.section in (1,2,3,4) 
   and b.sex in (1,2) 
   and b.age in (1,2,3,4,5,6,7) 
   and b.market in ('9','300')  
   and spot_key in ( '1:20141017:2129' )  
GROUP BY spot_key, market;

它给我与上面相同的输出。但我需要以下内容:

+-----------------+--------+---------------------+--------------------+
| spot_key        | market | panel_member        | TVR                |
+-----------------+--------+---------------------+--------------------+
| 1:20141017:2129 | 300    |                     |  0                 |
| 1:20141017:2129 | 9      | 010583010102;7.2930 | 134.65280079841614 |
+-----------------+--------+---------------------+--------------------+

1 个答案:

答案 0 :(得分:2)

您可以使用left join

执行此操作
SELECT spot_key, m.market, panel_member, SUM(weight) as TVR 
FROM (SELECT '9' as market UNION ALL SELECT '300'
     ) LEFT JOIN
     break_minute_tvr_fixed b 
     ON b.market = m.market and
        b.column1 in (1,3,4,2,3,4) and
        b.section in (1,2,3,4) and
        b.sex in (1,2) and
        b.age in (1,2,3,4,5,6,7) and
        b.spot_key in ( '1:20141017:2129' )  
GROUP BY spot_key, market;

当然spot_key将为NULL,除非您明确为其指定值:

SELECT '1:20141017:2129' as spot_key, m.market, panel_member, SUM(weight) as TVR