【问题标题】:MySQL JOIN using either NON-NULL column to reference another tableMySQL JOIN 使用任一 NON-NULL 列来引用另一个表
【发布时间】:2019-10-09 22:17:56
【问题描述】:

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

谁有更好的方法来查询这个?

【问题讨论】:

    标签: mysql sql join left-join


    【解决方案1】:

    您的查询逻辑很好。首先,请确保您有以下索引:

    locations(location_id1)
    locations(location_id2)
    events(location_id1)
    events(location_id2)
    

    如果索引已经就位,或者如果创建索引并没有显着提高性能,您可以尝试的一件事是使用WHERE 子句切换到两个LEFT JOINs,以确保其中一个连接匹配,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
    

    【讨论】:

    • 感谢朋友,当我使用“JOIN ON .. OR ..”时,查询时间为 1.6 秒(从没有“OR”的 0.06 秒开始)。这就是为什么我认为我的方法是个坏主意(已经有索引)
    • 不会使用第二个JOIN浪费资源吗?我希望有另一种方法可以做到这一点,但我喜欢你的“合并”技术
    • @NaturalBornCamper:这是一个建议,不确定它是否会提高性能。试试你的数据集,然后告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多