[英]How to combine these 2 SQL queries into one
我有一个两步查询,我试图将其合并为一个。
这将返回 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
)
;
但是,当我将上述 2 合并到一个查询中时,这不起作用并返回一组更短的结果:
----------------------
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))
)
;
我究竟做错了什么?
根据您的 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.