将子查询转换为自联接

时间:2014-04-16 18:04:01

标签: sql postgresql join self-join

我有这个查询,其中我想找到作者是Mr.X的每个作者的所有其他作者

我为此写的查询是:

SELECT DISTINCT (author_name) as AUTHORS 
    from table1 
    where title = (Select title from table1 where (author_name) = 'X');

我得到了错误:用作表达式

的子查询返回了多行

我认为要避免这种错误,我应该使用自我加入,但我无法弄清楚如何去做。

2 个答案:

答案 0 :(得分:3)

您的子查询返回的记录超过1条,在这种情况下,您无法使用=运算符而应该使用IN运算符来检查多个值,如下所示

where title in (Select title from table1 where (author_name) = 'X')

因此,您的查询应该看起来像

SELECT DISTINCT (author_name) as AUTHORS 
    from table1 
    where title in (Select title from table1 where (author_name) = 'X');

要将其更改为加入

SELECT DISTINCT (t1.author_name) as AUTHORS 
    from table1 t1
    join table1 t2
    on t1.title = t2.title

答案 1 :(得分:0)

额外的答案,在我看来,您的查询的效果可以改善使用:" count"

SELECT DISTINCT (author_name) as AUTHORS 
from table1 t1
where ISNULL((Select COUNT(t2.title) from table1 t2 where (author_name) = 'X' AND t1.title = t2.title), 0) > 0