【问题标题】:Optimization of 2 unrelated table join2个无关表连接的优化
【发布时间】:2017-04-22 09:21:33
【问题描述】:

我有一个界面,我将在其中显示来自 SQLite 数据库的项目列表,其中每个项目可以是以下两种类型之一:SubItem1SubItem2 。这个数据库目前有三个表:ItemsSubItem1SubItem2

Items 表包含 SubItemIdType 列(0 - SubItem1;2 - SubItem2)

SubItem1SubItem2 有不同的列,但大部分是相同的。

所以要使用填充此列表,我使用如下查询:

select i.*, s1.name, s2.name, s1.time, s2.place
from ITEMS i
left outer join sub1 s1 on (i.type = 0 and i.sub_id = s1.id)
left outer join sub2 s2 on (i.type = 1 and i.sub_id = s2.id)

我以这些列为例,但我选择了每个 SubItem 表的大约 10 列。

通过这个查询,我得到了很多冗余行。例如,当特定项目的类型为 SubItem1 时,我还将收到表 SubItem2 的空列

有没有更有效的方法来进行这个查询?

谢谢。

【问题讨论】:

  • 样本数据和期望的结果将有助于解释您想要完成的目标。

标签: sql sqlite join query-optimization redundancy


【解决方案1】:

COALESCE() 用于“相同”列:

select i.*, COALESCE(s1.name,s2.name) as name,
            COALESCE(s1.col1,s2.col2) as col2,
            ....
       s1.time, s2.place
from ITEMS i
left outer join sub1 s1 on (i.type = 0 and i.sub_id = s1.id)
left outer join sub2 s2 on (i.type = 1 and i.sub_id = s2.id)

【讨论】:

    【解决方案2】:

    您可以使用内连接分别选择这两种类型,然后将两种结果与compound query 结合起来:

    SELECT i.*, s.name, s.time, NULL AS place
    FROM Items AS i
    JOIN Sub1  AS s ON i.sub_id = s.id
    
    UNION ALL
    
    SELECT i.*, s.name, NULL,   s.place
    FROM Items AS i
    JOIN Sub2  AS s ON i.sub_id = s.id;
    

    这些可能更有效。

    【讨论】:

    • 感谢您打开我对使用 UNION 的想法。但结果显示不使用 UNION 时性能略有提升。
    猜你喜欢
    • 2019-12-30
    • 2016-12-10
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2021-08-18
    • 2016-10-16
    相关资源
    最近更新 更多