[英]MySQL JOIN using either NON-NULL column to reference another table
我有 2 個由 cronjobs 自動填充的表(一個事件表和一個包含事件地址的位置表。因為兩個提要不同,有時事件通過 location_id1 鏈接到位置,但有時使用 location_id2,如下所示:
locations table:
id imported_id1 imported_id2 address
1 NULL 20 xx
2 10 NULL xx
...
events table:
id location_id1 location_id2 some_data
1 NULL 20 xx
2 10 NULL xx
...
到 select 事件並獲取到它鏈接到的位置的正確地址,我嘗試了這樣的JOIN
,但是OR
使查詢運行慢得多:
SELECT * FROM events
JOIN locations ON
events.location_id1 = locations.limported_id1
OR events.location_id2 = locations.limported_id2;
有人有更好的方法來查詢這個嗎?
您的查詢邏輯很好。 首先,請確保您有以下索引:
locations(location_id1)
locations(location_id2)
events(location_id1)
events(location_id2)
如果索引已經到位,或者如果創建它們並沒有顯着提高性能,您可以嘗試的一件事是切換到兩個LEFT JOIN
並使用WHERE
子句確保其中一個連接匹配,並返回COALESCE()
來自匹配連接的地址,例如:
SELECT l.*, COALESCE(e1.address, e2.address) address
FROM locations l
LEFT JOIN events e1 ON e1.limported_id1 = l.location_id1
LEFT JOIN events e2 ON e2.limported_id2 = l.location_id2
WHERE e1.id IS NOT NULL OR e2.id IS NOT NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.