如何将这两个SQL查询合并为一个

时间:2019-10-01 01:03:11

标签: mysql

我有一个两步查询,我试图将其合并为一个查询。

这将返回ID:

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))
;

-然后,我将父ID = 26的结果(来自先前的查询)放入IN子句中。

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
)
;

但是,当我将上述两个查询组合到一个查询中时,这将不起作用,并且返回的结果要短得多:

----------------------
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))
)
;

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

Depending on your version of mysql,您可以使用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)
相关问题