选择未加入的记录以及已连接的记录

时间:2013-02-14 17:29:44

标签: mysql

您好我有以下格式的两张桌子:

表:

  ID   |  columnx | event |
  1    |     4    | call  |
  2    |     7    | call  |
  3    |     4    | call  |
  4    |     11   | visit |

B表:

columnx  | fName |
  4      | clare |
  7      | Bill  |
  9      | Tom   |
  11     | Nick  |

我做了如下查询:

Select A.columnx ,B.fName,Count(event) as Calls
from A
Left Join B on A.columnx = B.columnx 
where 'event' LIKE 'call';

它输出如下:

 columnx | fname  | Calls|
    4     | Clare  |   2  |
    7     | Bill   |   1  |
    11    | Nick   |   0  |

但我怎样才能得到以下输出:

 columnx  | fname  | Calls|
    4     | Clare  |   2  |
    7     | Bill   |   1  |
    11    | Nick   |   0  |
    9     | Tom    |   0  |

我的意思是当一个特定的记录没有加入时我需要选择计数为0的记录。这可以通过连接完成或者我需要找到另一种方式。有什么建议。谢谢。

2 个答案:

答案 0 :(得分:0)

将'event'LELKE'call'移至左连接的附加条件

    Select B.columnx ,B.fName ,Count(A.'event') as Calls
    from A
    Right Join B on A.columnx   = B.columnx   and A.'event' LIKE 'call'
    group by B.columnx  ,B.fName 
    order by B.columnx   

答案 1 :(得分:0)

您可以使用子查询来获取count()来电:

select dv.columnx,
  dv.fname,
  coalesce(dl.calls, 0) Calls
from device dv
left join
(
  select count(dl.event) Calls, dl.columnx
  from deal dl
  where dl.event LIKE 'call'
  group by dl.columnx
) dl
  on dv.columnx = dl.columnx

请参阅SQL Fiddle with Demo

或者,可以在没有子查询的情况下将WHERE过滤器移至JOIN

select dv.columnx,
  dv.fname,
  coalesce(count(dl.event), 0) Calls
from device dv
left join deal dl
  on dv.columnx = dl.columnx
  and dl.event LIKE 'call'
group by dv.columnx,  dv.fname

请参阅SQL Fiddle with Demo

返回:

| COLUMNX | FNAME | CALLS |
---------------------------
|       4 | clare |     2 |
|       7 |  Bill |     1 |
|       9 |   Tom |     0 |
|      11 |  Nick |     0 |