简体   繁体   中英

How to combine these 2 SQL queries into one

I have a 2-step query that I am trying to combine into one.

This returns the ids:

select  id
from    (select * from comments
        where deleted_at is NULL AND is_removed=0 and commentable_type LIKE "App%Comment"
         order by commentable_id, id) products_sorted,
        (select @pv := '26') initialisation
where   find_in_set(commentable_id, @pv)
and     length(@pv := concat(@pv, ',', id))
;

-- Then I take the results for parent id=26 (from prior query) and put them in an IN clause.

SELECT * FROM reactions 
WHERE deleted_at is NULL AND is_removed=0 AND reactable_type LIKE "App%Comment"
AND
reactable_id IN
(
30,
31,
33,
34,
50,
51,
52,
53,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
5819,
6083,
5921,
6390,
54,
56,
57,
58,
59,
60,
61,
62,
5779
)
;

However when I combine the above 2 into one query, this does NOT work and returns a much shorter set of results:

----------------------
SELECT * FROM reactions r
WHERE r.deleted_at is NULL AND r.is_removed=0 AND r.reactable_type LIKE "App%Comment"
AND
r.reactable_id IN
(
select  id
from    (select * from comments
        where deleted_at is NULL AND is_removed=0 and commentable_type LIKE "App%Comment"
         order by commentable_id, id) products_sorted,
        (select @pv := '26') initialisation
where   find_in_set(commentable_id, @pv)
and     length(@pv := concat(@pv, ',', id))
)
;

What am I doing wrong?

Depending on your version of mysql , you can use WITH

WITH
    first_query AS
    (

        select  id
        from    (select * from comments
                where deleted_at is NULL AND is_removed=0 and commentable_type LIKE "App%Comment"
                 order by commentable_id, id) products_sorted,
                (select @pv := '26') initialisation
        where   find_in_set(commentable_id, @pv)
        and     length(@pv := concat(@pv, ',', id))

    )

    SELECT
        *

    FROM
        reactions r

    WHERE
        r.deleted_at is NULL AND r.is_removed=0 AND r.reactable_type LIKE "App%Comment"
        AND
        r.reactable_id IN (SELECT DISTINCT * FROM first_query)

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