结合两个查询 - 如何?

时间:2012-01-17 13:45:22

标签: sql postgresql

我有以下疑问:

查询1:

Select * from T10,T11,T12,T13,T14 
where T10.C0 = T11.C0 and T11.C1 = T12.C0 
and T12.C1 = T13.C0 and T13.C1 = T14.C0; 

查询2:

Select * from T20,T21,T22,T23,T24 
where T20.C0 = T21.C0 and T21.C1 = T22.C0 
and T22.C1 = T23.C0 and T23.C1 = T24.C0;

如何组合这两个查询来显示这些表的所有值?我想要加入T10.C1 = T20.C1

尝试union时,我收到一条关于没有相同列数的警告,这是真的,这些表格不一样


联合

Select * from 
"ProductConfig","Board","PcbBuild","Model","TcssCalib" 
where "Model"."idModel" = "PcbBuild"."Model" and "Board"."PcbBuild" = "PcbBuild"."idPcbBuild" 
and "Board"."idBoard" = "TcssCalib"."Board" and "ProductConfig"."TcssCalib" = "TcssCalib"."idTcssCalib"

union

Select * from"ProductBuild","TxResultsLink","TxResults","DspValues" where "ProductBuild"."idProductBuild"
 = "TxResultsLink"."ProductBuild" and "TxResults"."idTxResults" = "TxResultsLink"."TxResults" 
and "TxResults"."DspValues" = "DspValues"."idDspValues";

这里我希望ProductBuild.Productconfig与ProductConfig.idProductConfig一起

给出错误:

[Err]错误:每个UNION查询必须具有相同的列数


当我尝试inner join时,我在inner

附近收到语法错误

有没有办法将这两个查询连接在一起?

1 个答案:

答案 0 :(得分:4)

这就是你想要的:

Select * from T10,T11,T12,T13,T14,T20,T21,T22,T23,T24
where T10.C0 = T11.C0 and T11.C1 = T12.C0 
and T12.C1 = T13.C0 and T13.C1 = T14.C0
and T10.C1 = T20.C1 and T20.C0 = T21.C0 and T21.C1 = T22.C0 
and T22.C1 = T23.C0 and T23.C1 = T24.C0;

另一种更易读的方式就是这样:

select * from T10
  inner join T11 on T10.C0 = T11.C0
  inner join T12 on T11.C1 = T12.C0 
  inner join T13 on T12.C1 = T13.C0 
  inner join T14 on T13.C1 = T14.C0
  inner join T20 on T10.C1 = T20.C1
  inner join T21 on T20.C0 = T21.C0
  inner join T22 on T21.C1 = T22.C0 
  inner join T23 on T22.C1 = T23.C0
  inner join T24 on T23.C1 = T24.C0;

要使UNION结果,表中的列数必须相同且来自相同/可转换的数据类型。

Select * from T10,T11,T12,T13,T14 
where T10.C0 = T11.C0 and T11.C1 = T12.C0 
and T12.C1 = T13.C0 and T13.C1 = T14.C0

UNION

Select * from T20,T21,T22,T23,T24 
where T20.C0 = T21.C0 and T21.C1 = T22.C0 
and T22.C1 = T23.C0 and T23.C1 = T24.C0;

Select * from 
"ProductConfig","Board","PcbBuild","Model","TcssCalib","ProductBuild","TxResultsLink","TxResults","DspValues"
where "Model"."idModel" = "PcbBuild"."Model" and "Board"."PcbBuild" = "PcbBuild"."idPcbBuild" 
and "Board"."idBoard" = "TcssCalib"."Board" and "ProductConfig"."TcssCalib" = "TcssCalib"."idTcssCalib" and "ProductBuild"."idProductBuild"
 = "TxResultsLink"."ProductBuild" and "TxResults"."idTxResults" = "TxResultsLink"."TxResults" 
and "TxResults"."DspValues" = "DspValues"."idDspValues"
and "ProductBuild"."ProductConfig" = "ProductConfig"."idProductConfig";
相关问题