我试图让作者满足EXISTS条件下的两个条件。但是,当子查询实际工作时,我会继续获取作者表中的所有条目。 谁能告诉我我的查询究竟出了什么问题?我目前正在计算参赛人数。
SELECT COUNT(*)
FROM author
WHERE
EXISTS (SELECT A.author_id, A.author_name
FROM author AS A
INNER JOIN author_publication AS AP ON A.author_id = AP.author_id
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/pvldb/%'
GROUP BY A.author_id
HAVING COUNT(*)>=10)
AND
EXISTS (SELECT A.author_id, A.author_name
FROM author AS A
INNER JOIN author_publication AS AP ON A.author_id = AP.author_id
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/sigmod/%'
GROUP BY A.author_id
HAVING COUNT(*)>=10)
;
答案 0 :(得分:2)
您的子查询与主查询没有任何关系。因此,对于每个记录,您都会问同一个问题:"表中是否存在至少十种特定类型的出版物的作者?"。每个记录的答案都是相同的,因此您可以获得所有记录。您真正想要问的是:"表中是否存在至少十种特定类型的出版物
SELECT COUNT(*)
FROM author
WHERE EXISTS
(
SELECT 1
FROM author_publication AS AP
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE AP.author_id = author.author_id
AND P.pub_key LIKE '%/pvldb/%'
GROUP BY AP.author_id
HAVING COUNT(*) >= 10
)
AND EXISTS
(
SELECT 1
FROM author_publication AS AP
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE AP.author_id = author.author_id
AND P.pub_key LIKE '%/sigmod/%'
GROUP BY AP.author_id
HAVING COUNT(*) >= 10
);
如果要编写非相关子查询,请改用IN
:
SELECT COUNT(*)
FROM author
WHERE author_id IN
(
SELECT AP.author_id
FROM author_publication AS AP
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/pvldb/%'
GROUP BY AP.author_id
HAVING COUNT(*) >= 10
)
AND author_id IN
(
SELECT AP.author_id
FROM author_publication AS AP
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/sigmod/%'
GROUP BY A.author_id
HAVING COUNT(*) >= 10
);
以下是如何使用单个子查询执行此操作:
SELECT COUNT(*)
FROM
(
SELECT AP.author_id
FROM author_publication AS AP
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/pvldb/%' OR P.pub_key LIKE '%/sigmod/%'
GROUP BY AP.author_id
HAVING COUNT(CASE WHEN P.pub_key LIKE '%/pvldb/%' THEN 1 END) >= 10
AND COUNT(CASE WHEN P.pub_key LIKE '%/sigmod/%' THEN 1 END) >= 10
) found_authors;
答案 1 :(得分:0)
尝试:
SELECT COUNT(A.author_id)
FROM
author AS A
INNER JOIN author_publication AS AP ON A.author_id = AP.author_id
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE
P.pub_key LIKE '%/pvldb/%' OR P.pub_key LIKE '%/sigmod/%'
GROUP BY A.author_id
HAVING COUNT(A.author_id) >= 10;
答案 2 :(得分:0)
您只需要将子查询与主查询相关联:
SELECT COUNT(*)
FROM author as AA
WHERE
EXISTS (SELECT A.author_id, A.author_name
FROM author AS A
INNER JOIN author_publication AS AP ON A.author_id = AP.author_id
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/pvldb/%'
AND AA.author_id=A.author_id
GROUP BY A.author_id
HAVING COUNT(*)>=10)
AND
EXISTS (SELECT A.author_id, A.author_name
FROM author AS A
INNER JOIN author_publication AS AP ON A.author_id = AP.author_id
INNER JOIN publication AS P ON AP.pub_id = P.pub_id
WHERE P.pub_key LIKE '%/sigmod/%'
AND AA.author_id=A.author_id
GROUP BY A.author_id
HAVING COUNT(*)>=10)
;