简体   繁体   English

连接具有相同字段的两个表

[英]Join between two tables with same fields

i have these tho tables:我有这些表:

FT
id|Rif1|Rif2|CodCli|Data1|Data2

and

FR
id|Rif1|Rif2|Qta|Price

I would like to join results filtering from Codcli using Rif1 and Rif2 from both tables (that contain the same values) I do this:我想使用来自两个表(包含相同值)的 Rif1 和 Rif2 加入从 Codcli 过滤的结果,我这样做:

SELECT FT."Rif1", FR."Rif1", FT."Rif2", FR."Rif2", "Data1", "Data2", "Qta", "Price", "CodCli"
FROM FT, FR
WHERE FT."CodCli" = '653' AND (FT."Rif1" = FR."Rif1" AND FT."Rif2" = FR."Rif2");

But the result is wrong, I would like all data from table FT related to the filtered Codcli but with in addition the data from table FR joined by Rif1 and Rif2 related fields.但结果是错误的,我想要表 FT 中与过滤后的 Codcli 相关的所有数据,但另外还有来自表 FR 的数据由 Rif1 和 Rif2 相关字段连接。

I would like all data from table FT related to the filtered Codcli我想要表 FT 中与过滤后的 Codcli 相关的所有数据

This sounds like a LEFT JOIN :这听起来像一个LEFT JOIN

SELECT FT."Rif1", FR."Rif1", FT."Rif2", FR."Rif2", 
       "Data1", "Data2", "Qta", "Price", "CodCli"
FROM FT LEFT JOIN
     FR
     ON FT."Rif1" = FR."Rif1" AND FT."Rif2" = FR."Rif2"
WHERE FT."CodCli" = '653';

Try using LEFT JOIN if this works for you:如果这对您有用,请尝试使用 LEFT JOIN:

SELECT FT."Rif1", FR."Rif1", FT."Rif2", FR."Rif2", "Data1", "Data2", "Qta", "Price", "CodCli"
FROM FT LEFT JOIN FR ON FT."Rif1" = FR."Rif1" AND FT."Rif2" = FR."Rif2" where FT."CodCli" = '653';

In your case postgresql select data from second table then get all data from first table with your where condition.在您的情况下,postgresql 从第二个表中选择数据,然后使用您的 where 条件从第一个表中获取所有数据。 Thats way you are getting wrong result.这样你就会得到错误的结果。 Use left join .使用left join In this case system gets data from first table with condition then joins second table.在这种情况下,系统从具有条件的第一个表中获取数据,然后加入第二个表。 So所以

SELECT FT."Rif1", FR."Rif1", FT."Rif2", FR."Rif2", "Data1", "Data2", "Qta", "Price", "CodCli"
FROM FT
LEFT JOIN FR ON FT."Rif1" = FR."Rif1" AND FT."Rif2" = FR."Rif2"
WHERE FT."CodCli" = '653';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM