1

假设我有 2 个表:Human,Car。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??
4

4 回答 4

1

Car尝试按 对您的记录进行分组Human_id,然后查看该HAVING子句。

于 2012-05-28T13:51:04.453 回答
1
SELECT human.name, car.human_id, count(*) as total
FROM Human, Car
group by human.name, car.human_id
having count(*) > 1
于 2012-05-28T14:28:43.130 回答
0

如果您在HumanCar表之间有 FK ,最好使用Join而不是笛卡尔积:

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

我希望我能帮助你

于 2012-05-29T11:26:39.393 回答
-1
 select human.name
 from human
 where human.id in
      select human.id
      from car
      where count(car) > 1
      group by human.id
于 2012-05-28T13:51:34.737 回答