简体   繁体   中英

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM