获取与左连接表匹配的行数?

时间:2018-07-31 10:52:52

标签: mysql sql

我有下表:

Persons  
|id   |firstname|lastname|  
|-----|---------|--------|  
|1    |John     |Doe     |  
|2    |Jim      |Smith   |  
|3    |Jane     |Boggard |  
|4    |Joe      |Dash    |  


Vehicles
|p_id |type   |
|-----|-------|
|1    |car    |
|1    |bike   |
|1    |car    |
|2    |car    |
|3    |car    |
|3    |bike   |
|4    |plane  |

我想找到一种获取每个人的汽车数量的方法(即:与“车辆”联接表匹配的行数)。 我在联接表中尝试了一个涉及COUNT的子查询,但结果错误。
我期望的结果看起来像这样:

|firstname|lastname|nb_cars|  
|---------|--------|-------|
|John     |Doe     |2      |  
|Jim      |Smith   |1      | 
|Jane     |Boggard |1      |  
|Joe      |Dash    |0      |

我该如何实现?

4 个答案:

答案 0 :(得分:0)

您必须使用joingroup by子句,例如:

SELECT p.firstname, p.lastname, count(v.p_id) AS nb_cars
FROM Persons p
JOIN Vehicles v ON p.id = v.p_id
GROUP BY p.id

答案 1 :(得分:0)

尝试一下:

select *,
       (select count(*) from Vehicles
        where p_id = p.id and type = 'car')
from Persons p'

答案 2 :(得分:0)

尝试一下

Select p.firstname, p.lastname, count(v.p_id) as no_of_car
From Persons p left join Vehicles v on (p.id = v.p_id and v.type = 'car')
group by p.firstname, p.lastname

答案 3 :(得分:0)

执行左联接和aggregate sum功能

   select p.firstname, p.lastname, 
   sum(case when v.type='car' then 1 else 0 end) as nb_cars
    from Persons p
    left outer join Vehicles v on p.id = v.p_id

    group by p.id, p.firstname, p.lastname

firstname   lastname    nb_cars
John        Doe          2
Jim         Smith        1
Jane        Boggard      1
joe         Dash         0

http://sqlfiddle.com/#!9/016d72/1