Skip to content
Advertisement

Subquery on SELECT with conditional WHERE clause after it

So I have three tables,

news :

topics :

and news_topics :

And I want to return it like these :

I succeed on returning that value using this query

But there is one flaw to that query, on the above result there are one row that contains null topics. When I add AND topics IS NOT NULL after it gave me error SQL Error [42703]: ERROR: column "topics" does not exist it is makes sense because the order of the query SQL executed.

I want rows that had null value on topics aren’t included on the query result. How do I get that?

Advertisement

Answer

Instead of using a correlated subquery to get the column topics, aggregate on the joined tables topics and news_topics and then join to news:

See the demo.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement