0

我有一个项目,我必须使用嵌套选择和 EXISTS、IN、ALL、ANY 等运算符来查找拥有更多公寓的业主的姓名。

我有 2 桌业主和公寓

Owner
"ID" NUMBER(5,0), 
"NAME" VARCHAR2(20), 
"PHONE" NUMBER(10,0),
CONSTRAINT "PROPR" PRIMARY KEY ("ID")
USING INDEX  ENABLE; 

Apartment
"ID_AP" NUMBER(5,0), 
"ADDRESS" VARCHAR2(35), 
"SURFACE" NUMBER(10,0),
"ID" NUMBER(5,0),
CONSTRAINT "APART" PRIMARY KEY ("ID_AP")
USING INDEX  ENABLE;

为了找到拥有不止一套公寓的业主,我写了这个

SELECT name, id, count(id)
from apartment join owner
using (id)
group by id, name
having count(id)>1

但是如何使用嵌套的 Selects 和 EXISTS、IN、ALL、ANY 运算符之一?

4

3 回答 3

0
WITH myView(name, id,appcount)
as
SELECT name, id, (select count(id) FROM apartment where id = ow.id) 
FROM owner ow

SELECT * from myView
WHERE appcount > 2

使用 WITH 创建内联视图并用于编写查询。(select count(id) FROM apartment where id = ow.id) 在外部查询的选择中将计算公寓数量。

于 2016-11-30T13:00:51.390 回答
0

例如像这样:

select * from owner where id IN (
    SELECT id
    from apartment 
    group by id
    having count(id)>1)
于 2016-11-30T12:44:25.917 回答
0

我不太确定您编写的查询是否正确。

您提供的正确查询将 count(id_ap) 而不是 count(id)

SELECT o.id, o.name, count(a.id_ap)
from apartment a
join owner o on o.id = a.id
group by o.id, o.name
having count(a.id_ap)>1

使用in子句的相同查询,但没有公寓数量,您只知道它是2个或更多

select o.id, o.name
from owner o
where o.id in (select distinct(a.id) from apartment a
group by a.id having count(a.id_ap) > 1);

您也缺少引用所有者表的公寓表的外键约束。

于 2016-11-30T12:46:57.307 回答