我在尝试使用(union / intersect / minus)计算主键ACNUM在这些表中的次数时遇到了一些困难。
我尝试了多种使用SET运算符的方法,但似乎无法弄明白。
即使是这样的事情似乎也不起作用:
SELECT results.ACNUM, COUNT(results.books), COUNT(results.interests)
FROM (
SELECT ACNUM FROM ACADEMIC A
UNION
SELECT COUNT(PANUM) as books FROM AUTHOR B
UNION
SELECT COUNT(FIELDNUM) as interests FROM INTEREST C
) results;
基本上,我需要将此查询(有效)转换为上面的查询,我使用set运算符。
SELECT DISTINCT ACNUM
FROM ACADEMIC A
WHERE
(SELECT COUNT(PANUM)
FROM AUTHOR
WHERE ACNUM = A.ACNUM) < 5
AND
(SELECT COUNT(FIELDNUM)
FROM INTEREST
WHERE ACNUM = A.ACNUM) > 3;
答案 0 :(得分:1)
我不知道为什么你坚持使用集合运算符,但INTERSECT将返回预期结果:
SELECT ACNUM
FROM ACADEMIC A
INTERSECT
SELECT ACNUM
FROM AUTHOR
GROUP BY ACNUM
HAVING COUNT(PANUM) < 5
INTERSECT
SELECT ACNUM
FROM INTEREST
GROUP BY ACNUM
HAVING COUNT(FIELDNUM) > 3;
答案 1 :(得分:0)
您以错误的方式使用了 UNION 查询,因为Ist查询中的内部查询只生成了一列,而您从中获取了三列。
你可以在这里使用join,如下所示:
select a.ACNUM, count(ar.PANUM), count(i.FIELDNUM)
from ACADEMIC a join AUTHOR ar on a.ACNUM=ar.ACNUM
join INTEREST i on a.ACNUM=i.ACNUM
group by a.ACNUM
having count(ar.PANUM)<5 and count(i.FIELDNUM)>3;
答案 2 :(得分:0)
SELECT X.ACNUM, Y.books, Z.interests
FROM (
(SELECT ACNUM FROM ACADEMIC A)X
LEFT JOIN
(SELECT COUNT(PANUM) as books FROM AUTHOR B)Y
ON X.ACNUM=Y.ACNUM
LEFT JOIN
(SELECT COUNT(FIELDNUM) as interests FROM INTEREST C)Z
ON X.ACNUM=Z.ACNUM ) WHERE Y.books<5 and Z.interests>3;