我正在尝试编写查询,但我不确定我尝试做的是否正确。我解释这个的最好方法是向你展示我想要的和我拥有的东西
我想要的是什么:
ID | SomeCol1 | SomeCol2 | Fish | Cat
-------------------------------------
1 foo bar baz boz
2 foo2 bar2 baz2 boz2
我有什么:
select
tblA.id as "ID",
tblB.someCol as "SomeCol1",
tblD.someOtherCol as "SomeCol2"
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
这正确地给了我前3列。
这个单独的查询为我提供了'Fish'
的正确列/值select tblE.someCol as "Fish"
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
where tblD.someOtherColumn = 'Fish';
我会使用相同的表格为猫做一个类似的。
但是,如果我尝试通过嵌套选择来组合查询,那么我显然会得到“单行子查询返回超过1行”错误。
select
tblA.id as "ID",
tblB.someCol as "SomeCol1",
tblD.someOtherCol as "SomeCol2",
(select tblE.someCol as "Fish"
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
where tblD.someOtherColumn = 'Fish'),
(select tblE.someCol as "Cat"
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
where tblD.someOtherColumn = 'Cat')
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
那么,我怎么能正确地做到这一点?还有一种方法只引用一次表而不是多次,如上所示? *我的真实世界查询更复杂,有更多的表可以加入,还有15个左右的列必须执行与'Fish'列相同的逻辑。
谢谢!
**更新 - 我想我已经明白了。我需要使用'with'命令创建一次子查询。然后我创建了子查询:
with v_tbl as (
select *
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
), v_fish as (select name from v_tbl where tblD.someOtherColumn = 'Fish')
, v_cat as (select name from v_tbl where tblD.someOtherColumn = 'Cat')
select <regular query stuff>...
答案 0 :(得分:0)
除非我遗漏了什么,否则我不明白为什么你需要一个子查询:
select
tblA.id as "ID",
tblB.someCol as "SomeCol1",
tblD.someOtherCol as "SomeCol2",
tblE.someCol as "Fish"
from TableA tblA
inner join TableB tblB on tblA.fkId1=tblB.id
inner join TableC tblC on tblA.id=tblC.fkId2
inner join TableD tblD on tblC.fkId8=tblD.id
inner join TableE tblE on tblC.fkId9=tblE.id
where tblD.someOtherColumn = 'Fish';
答案 1 :(得分:0)
我相信我已经解决了问题并在原帖中发布了答案