WHOATEMYNOODLES
WHOATEMYNOODLES

Reputation: 897

Union on this subquery

How would I union the results from the first query t1 and then on the subquery t2

SELECT * FROM comments t1
WHERE parent_id IN
(SELECT comment_id FROM comments t2 WHERE e_id = 1 AND parent_id is null)

Upvotes: 0

Views: 130

Answers (2)

Dylon
Dylon

Reputation: 1750

My postgresql is a little rusty, but I believe something like this should work:

WITH t2 AS (
  SELECT *
  FROM comments
  WHERE e_id = 1
    AND parent_id IS NULL
), t1 AS (
  SELECT *
  FROM comments
  WHERE parent_id IN (
    SELECT comment_id
    FROM t2
  )
)
SELECT * FROM t1
UNION
SELECT * FROM t2

Upvotes: 2

Ed Bangga
Ed Bangga

Reputation: 13026

if you are going to merge or use union not union all, you can consider this query.

select * from comments
where (1=1 or parent_id = case when e_id = 1 and parent_id is null then comment_id end)

Upvotes: 0

Related Questions