我们假设我有两张桌子:人,车。 Table Car有一些列,其中一列是Human_id。例如,像这样:
Human_id Type
1 BMW
5 Mercedes
1 Audi
2 Peugeot
3 BMW
2 JEEP
如何选择所有拥有多辆车的人?我的意思是我需要控制在Human_id列中是否多次使用Human_id。但我怎么能这样做?
SELECT human.name
FROM Human, Car
WHERE .... <- what goes here??
答案 0 :(得分:1)
尝试按Car
对Human_id
条记录进行分组,并查看HAVING
条款。
答案 1 :(得分:1)
SELECT human.name, car.human_id, count(*) as total
FROM Human, Car
group by human.name, car.human_id
having count(*) > 1
答案 2 :(得分:0)
如果 Human 和 Car 表之间有FK,最好使用加入而不是笛卡尔积:
create table Human (
idHuman integer primary key,
name varchar(15),
...
);
insert into Human (idHuman, name) values
(1,'A'), (2,'B'), (3,'C'), (4,'D'), (5,'E');
create table Car (
Human_id integer REFERENCES Human ON DELETE CASCADE,
Type varchar(15),
...
);
insert into Car (Human_id, Type) values
(1,'BMW'), (5,'Mercedes'), (1,'Audi')
,(2,'Peugeot'), (3,'BMW'), (2,'JEEP');
查询:
select hu.name
from Human hu
join Car ca on (ca.Human_id = hu.idHuman)
group by hu.name
having count(*) > 1
我希望我帮助你
答案 3 :(得分:-1)
select human.name
from human
where human.id in
select human.id
from car
where count(car) > 1
group by human.id