我有一个界面,在其中我将显示 SQLite 数据库中的项目列表,每个项目可以是两种类型之一:SubItem1 和 SubItem2 。该数据库当前有三个表:Items、SubItem1 和 SubItem2。
表Items包含列SubItemId和Type(0 - SubItem1;2 - SubItem2)
SubItem1 和 SubItem2 具有不同的列,但其中很多是相同的。
因此,要使用填充此列表,我使用如下查询:
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 的空列
是否有更有效的方法来进行此查询?
谢谢。
最佳答案
对“相同”列使用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)
关于sql - 2. 不相关表连接的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017350/