简体   繁体   中英

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:

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.

I would like all data from table FT related to the filtered Codcli

This sounds like a 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:

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. Thats way you are getting wrong result. Use 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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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