我在小提琴中有如下查詢。
select * from notification where status = 0 and (
notif_id in (select notif_id from notif_user where user_id = 1) OR
notif_id in (select notif_id from notif_group where group_id = 1))
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=cad284e77218eb37461e60b6308bf85f
查詢按預期作業。但是,查詢會有任何性能問題。是否可以使用 Join 轉換內部查詢?
謝謝
uj5u.com熱心網友回復:
您可以將子查詢表示為聯合并比較執行計劃統計資訊。查看fiddle中的輸出,聯合似乎表現稍好一些。
select *
from notification
where status = 0 and (
notif_id in (
select notif_id from notif_user where user_id = 1 union all
select notif_id from notif_group where group_id = 1
)
);
另一種表達方式是使用存在
select *
from notification n
where status = 0 and
(
exists (select * from notif_user nu where nu.user_id = 1 and nu.notif_id = n.notif_id)
or exists(select * from notif_group ng where ng.group_id = 1 and ng.notif_id = n.notif_id)
);
uj5u.com熱心網友回復:
您的子查詢不是依賴子查詢,它們是獨立的。也就是說,它們不參考表中的列notification,而只參考它們自己表中的列。
所以這里沒有性能問題。
uj5u.com熱心網友回復:
這是相同的查詢撰寫為沒有子查詢的連接。
但是,我預計性能會受到負面影響。
select distinct n.*
from notification n
left join notif_user u
on n.notif_id = u.notif_id
left join notif_group g
on n.notif_id = g.notif_id
where status = 0
and (user_id = 1
or group_id = 1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/444083.html
標籤:mysql
下一篇:從產品到訂單的總價格
