MySQL JOIN使用任一NON-NULL列来引用另一个表



>我有 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

最新更新