kp123
kp123

Reputation: 1330

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?

Upvotes: 0

Views: 30

Answers (1)

artemis
artemis

Reputation: 7261

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)

Upvotes: 1

Related Questions