首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >两个无关表连接的优化

两个无关表连接的优化
EN

Stack Overflow用户
提问于 2016-12-07 12:20:08
回答 2查看 78关注 0票数 2

我有一个接口,在其中我将显示来自SQLite数据库的项目列表,每个项目可以是两种类型中的一种:SubItem1SubItem2。该数据库目前有三个表:ItemSubItem1SubItem2

Item包含SubItemId类型 (0 - SubItem1;2- SubItem2)列。

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

因此,为了使用填充这个列表,我使用了如下查询:

代码语言:javascript
复制
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的空列

是否有更有效的方法来进行此查询?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-07 12:24:33

对“相同”列使用COALESCE()

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-12-07 14:28:46

可以使用内部联接分别选择这两种类型,然后将这两种结果与复合查询组合起来。

代码语言:javascript
复制
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;

这可能会更有效率。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41017350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档