我需要帮助编写一个SQL语句(我在这里有一个高级时刻): 设备表包含库存中的所有项目:
Tables -
Equip: EquipID, Barcode, ModelRefId.
Model: ModelID, AcceptsCards, MakeRefId.
Make: MakeId.
我有另一张桌子,“内容”,其中包含“接受卡片”的物品的装备,然后是该物品内的每个EquipId的列表:
Contents: EquipRefId, EquipCardRefId.
example: 100 1000
100 1001
101 1002
101 1003
...
我想创建一个声明来返回接受卡的所有项目(设备)(WHERE Model.AcceptsCards = true),以及项目中的任何卡(也是设备)(基本上是空PC机箱列表) ,所有PC卡的列表,然后内容是该PC中的PC ID和卡。
PC1 Make Model Barcode
Card1 Make Model Barcode
Card2 Make Model Barcode ....etc...
PC2 Make Model Barcode
Card1 Make Model Barcode
Card2 Make Model Barcode ....etc...
...etc...
要退回所有接受卡的设备(例如所有PC机箱):
SELECT Make.sMakeName, Model.sModelName, Make.iMakeID, Model.iModelID, Equip.iEquipID, Equip.sBarcode, Equip.sSerialNo
FROM Equip RIGHT OUTER JOIN
Make LEFT OUTER JOIN
Model ON Make.iMakeID = Model.iMakeRef ON Equip.iModelRef = Model.iModelID
WHERE (Model.iAcceptsCards = 1)
ORDER BY Make.sMakeName, Model.sModelName
..但我不知道如何包含/合并/加入Contents表。
答案 0 :(得分:0)
如果我找对你,你有第一个查询(所有接受卡片的设备),并希望根据第一个查询(第一个查询中每个项目的内容)添加第二个查询的结果结果)。
基本上有两种不同的方式。 在您的情况下,Query_A就像
select Id_A, Make_A, Model_A, Barcode_A
from [some joining of tables Equip, Model, Make] ...
where ...
而Query_B就像
select Id_B, Make_B, Model_B, Barcode_B
from Query_A
join Contents on ...
join [some joining of tables Equip, Model, Make] ...
where ...
首先,如果您需要像问题中那样订购结果,则必须确保Query_B具有Query_A的Id列,您可以将其用于将每个父项及其内容组合在一起。
第一种方式只是结合两个查询的结果:
select *
from (
select Id_A, Id_A as Id, Make_A, Model_A, Barcode_A
from [some joining of tables Equip, Model, Make] ...
where ...
union all
select Id_A, Id_B, Make_B, Model_B, Barcode_B
from (
select Id_A
from [some joining of tables Equip, Model, Make] ...
where ...
) as Query_A
join Contents on ...
join [some joining of tables Equip, Model, Make] ...
where ...
) x
order by Id_A, Id
如果您的服务器支持CTE
,则可以简化声明:
with Query_A as (
select Id_A, Make_A, Model_A, Barcode_A
from [some joining of tables Equip, Model, Make] ...
where ...
)
select Id_A, Id_A, Make_A, Model_A, Barcode_A
from Query_A
union all
select Id_A, Id_B, Make_B, Model_B, Barcode_B
from Query_A
join Contents on ...
join [some joining of tables Equip, Model, Make] ...
where ...
第二种方式是复制第一个查询的结果,然后将每个双重转换为其内容:
select
case x.x when 0 then Query_A.Id_A else Id_B end as Id,
case x.x when 0 then Query_A.Make_A else Make_B end as Make,
case x.x when 0 then Query_A.Model_A else Model_B end as Model,
case x.x when 0 then Query_A.Barcode_A else Barcode_B end as Barcode
from (
select Id_A, Make_A, Model_A, Barcode_A
from [some joining of tables Equip, Model, Make] ...
where ...
) as Query_A
cross join (select 0 as x union all select 1) as x
left join Contents on (x.x = 1 and ...)
left join [some joining of tables Equip, Model, Make] ...
where (x.x = 0 or Id_B is not null) and ...
order by Id_A, Id