加入Sqlite中介表

时间:2017-04-07 13:05:00

标签: sqlite

我的sqlite数据库中有这个模式

CREATE TABLE `CARS` (
    `ID`    INTEGER,
    `Name`  TEXT,
    PRIMARY KEY(ID)
);

CREATE TABLE `OWNERS` (
`ID`    INTEGER,
`Name`  TEXT,
PRIMARY KEY(ID)
);

OWNERS表和CARS表之间的中间表

CREATE TABLE `OwnerCars` (
    `OwnerId`   INTEGER,
    `CarId` INTEGER,
    PRIMARY KEY(OwnerId,CarId),
    FOREIGN KEY(`OwnerId`) REFERENCES `Owners`(`Id`),
    FOREIGN KEY(`CarId`) REFERENCES `Cars`(`Id`)
);

询问这个我只会得到拥有汽车和车辆数量的车主

select ownerid, count(carid) as carscount from OwnerCars 
                            inner join Owners on ownerid = id
                            group by(ownerid) 

我怎样才能让所有车主(包括没有车的人和他们的车数为0 )。 谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

对查询使用Left Outer Join,同时将所有者表保留在左侧。

select o.id, count(carid) as carscount 
from owner o
Left Outer join OwnerCars on ownerid = o.id
group by(o.id) 

答案 1 :(得分:0)

select OWNERS.ID, count(OwnerCars.CarId) as carscount
from OWNERS Left Outer join OwnerCars on OwnerCars.OwnerId=OWNERS.ID
group by(OWNERS.ID);