我有 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
...
为了选择事件并获取其链接到的位置的正确地址,我尝试了像这样的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
关于MySQL JOIN 使用任一非空列来引用另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313008/