使用多個表進行MySQL連接,避免使用子查詢方法
P粉442576165
P粉442576165 2023-09-07 17:38:48
0
2
450

我在fiddle的查詢如下。

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

查詢按預期工作。但是,查詢是否會有任何效能問題。是否可以將內部查詢轉換為連線?

P粉442576165
P粉442576165

全部回覆(2)
P粉567281015

您的子查詢不是依賴子查詢,而是獨立的。也就是說,它們不引用您的notification表中的列,而只引用它們自己表中的列。

所以這裡沒有效能問題。

P粉576184933

您可以將子查詢表示為聯合查詢,並比較執行計劃統計資料。看看fiddle中的輸出,union似乎執行稍微更好。

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

另一種表達方式是使用exists

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)
);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!