我的表格TContractForm
包含字段idcontract(primary key),idcntrtype(foreign key),date_begin,date_end,cost
。我还有3种类型的合同:
TRentWhouseContract
的 idcontract,idclient,idpdtwhs
带有字段TRentShoppointContract
idcontract,idclient,idshoppoint,idshoptype
带有字段TRentEquipContract
idcontract,idclient,ideq,amount
idcntrtype
- 合同类型。 TContractType
- idcntrtype(primary key),idcntrclass(foreign key),name
。 TContractClass
- idcntrclass,name
。
我想创建一个包含列的视图
idcontract,idclient,contract_type(name of type),contract_class(name of class),date_begin,date_end,cost
。
但我的查询没有返回任何内容(我知道我在TRentWhouseContract表中有多个合同(其他表没有行)(它没有idclient因为我不知道如何从不同的表中获取相同的idclient,如果有一些表是空的。
select TCF.idcontract,
--idclient
TCF.date_begin,
TCF.date_end,
TCT.name as [type],
TCC.name as class,
TCF.cost
from TContractForm as TCF,
TRentEquipContract as TREC,
TRentShopPointContract as TRSPC,
TRentWhouseContract as TRWC,
TContractType as TCT,
TContractClass as TCC
where TCF.idcontract = TREC.idcontract or TCF.idcontract = TRSPC.idcontract
or TCF.idcontract = TRWC.idcontract and TCT.idcntrtype = TCF.idcntrtype
and TCT.idcntrclass = TCC.idcntrclass
答案 0 :(得分:2)
如果我理解正确,这就是我要做的事情
select TCF.idcontract,
--idclient
TCF.date_begin,
TCF.date_end,
TCT.name as [type],
TCC.name as class,
TCF.cost
from TContractForm as TCF
JOIN TContractType as TCT
ON TCT.idcntrtype=TCF.idcntrtype
JOIN TContractClass as TCC
ON TCT.idcntrclass = TCC.idcntrclass
UNION
select TCF.idcontract,
--idclient
TCF.date_begin,
TCF.date_end,
TCT.name as [type],
TCC.name as class,
TCF.cost
from TRentWhouseContract as TCF
JOIN TContractType as TCT
ON TCT.idcntrtype=TCF.idcntrtype
JOIN TContractClass as TCC
ON TCT.idcntrclass = TCC.idcntrclass
UNION
select TCF.idcontract,
--idclient
TCF.date_begin,
TCF.date_end,
TCT.name as [type],
TCC.name as class,
TCF.cost
from TRentShoppointContract as TCF
JOIN TContractType as TCT
ON TCT.idcntrtype=TCF.idcntrtype
JOIN TContractClass as TCC
ON TCT.idcntrclass = TCC.idcntrclass
UNION
select TCF.idcontract,
--idclient
TCF.date_begin,
TCF.date_end,
TCT.name as [type],
TCC.name as class,
TCF.cost
from TRentEquipContract as TCF
JOIN TContractType as TCT
ON TCT.idcntrtype=TCF.idcntrtype
JOIN TContractClass as TCC
ON TCT.idcntrclass = TCC.idcntrclass
答案 1 :(得分:1)
如何获得idclient:
coalesce(TREC.idclient, TRSPC.idclient,TRWC.idclient) as idclient
Coalesce返回第一个非缺失值。
至于其余部分 - 我认为你应该做左外连接而不是逗号连接,因为你没有所有表中的一些记录(好吧,所有表中都没有记录!)。
select...
from TCF,TCT,TCC ... A
left join ... TREC on A.idcontract=TREC.idcontract
left join ... TRSPC
等