0

I have this query in which i want to find who are all the other authors are for each title in which the author is Mr.X

The query I wrote for that is:

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

I got the ERROR: more than one row returned by a subquery used as an expression

I think to avoid this error i should use a self join but I'm not able to figure out how to do it.

2 Answers 2

3

your subquery returning more than 1 record and in such case you can't use = operator rather You should use IN operator to check against multiple values like below

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

So, your query should look like

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

To change it to join instead

SELECT DISTINCT (t1.author_name) as AUTHORS 
    from table1 t1
    join table1 t2
    on t1.title = t2.title
Sign up to request clarification or add additional context in comments.

Comments

0

An extra answer, in my opinion the performance of your query improves using: "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

1 Comment

In a case when I need to "play" with a lot of data I prefer to use a "count" in a subquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.