[英]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.