我有两个桌子
CREATE TABLE `Company` (
`companyName` TEXT,
`status` TEXT,
`extra` TEXT,
`companyId` TEXT,
`companySecondId` TEXT
CREATE TABLE `UserList` (
`userName` TEXT,
`companyId` TEXT
);
我想使用CompanyId加入UserList和Company
数据示例)
companyName status extra companyId companySecondId
"CompanyA" "456" "456" "A" "A"
"CompanyB" "789" "789" "B" "A"
"CompanyC" "123" "123" "C" "E"
"CompanyD" "111" "111" "D" "D"
UserName CompanyId
"UserA" "A"
"UserB" "B"
"UserC" "C"
"UserD" "D"
这是情况。
公司可以合并 CompanyB合并到A
公司可能破产 CompanyC已合并到CompanyE,但是CompanyE破产了。
在这种情况下,我是这样加入的
select UserList.*, t1.companyName
from UserList
inner join
(select companyId,
(case when exists (select * from Company where a.companySecondId = companyId)
then (select companyName from Company where a.companySecondId = companyId)
else (select companyName from Company where a.companyId = companyId)
end) as companyName
from Company a) as t1
on UserList.companyId = t1.companyId
如果每个用户的companyId在公司表中都存在“ companySecondId”,则显示companySecondId的companyName
如果每个用户的companyId在公司表中都不存在且带有“ companySecondId”,则显示companyId的companyName而不是companySecondId
所以我可以得到这样的结果
userName companyId companyName
"UserA" "A" "CompanyA"
"UserB" "B" "CompanyA"
"UserC" "C" "CompanyC"
"UserD" "D" "CompanyD"
但是我想展示状态和其他类似内容 但是如果存在的话〜那么〜否则仅返回一列。如何在SQLite中做到这一点?
userName companyId companyName status extra
"UserA" "A" "CompanyA" "456" "456"
"UserB" "B" "CompanyA" "456" "456"
"UserC" "C" "CompanyC" "123" "123"
"UserD" "D" "CompanyD" "111" "111"
答案 0 :(得分:0)
问题中的逻辑有点难以理解。但是,我认为您只是在寻找left join
:
select ul.userName,
coalesce(c2.companyId, c.companyId) as companyId,
coalesce(c2.status, c.status) as status,
coalesce(c2.extra, c.extra) as extra
from userlist ul left join
company c
on ul.companyId = c.companyId left join
company c2
on c2.companyId = c.companySecondId;
第二个left join
在这里主要是查看表中是否存在第二个公司。