0

我有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),nameTContractClass- idcntrclass,name

我想用 columns 创建一个视图 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
4

2 回答 2

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
于 2012-12-14T18:29:25.963 回答
1

如何获取idclient:

coalesce(TREC.idclient, TRSPC.idclient,TRWC.idclient) as idclient

合并返回第一个非缺失值。

至于其余的 - 我认为你应该做左外连接而不是逗号连接,因为你没有所有表中的一些记录(好吧,所有表中都没有记录!)。

select...
from TCF,TCT,TCC ... A
 left join ... TREC on A.idcontract=TREC.idcontract
 left join ... TRSPC 

等等

于 2012-12-14T18:28:06.083 回答