我有一个界面,我将在其中显示 SQLite 数据库中的项目列表,每个项目可以是以下两种类型之一: SubItem1 和 SubItem2 即可。此数据库目前有三个表:项, SubItem1 和 SubItem2 。
表项包含 SubItemId 列和类型(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列。
通过此查询,我获得了大量冗余行。例如,当Type为特定Item的SubItem1时,我也将接收表SubItem2的空列
是否有更有效的方法来进行此查询?
感谢。
答案 0 :(得分:0)
将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)
答案 1 :(得分:0)
您可以使用内部联接单独选择这两种类型,然后将结果与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;
这些可能更有效率。