简体   繁体   中英

How can I do this SQL query correctly?

I've got an SQL table that has 3 fields, all are ids and all are foreign keys, however, the first two fields reference the same field in another table. I need to show this table with the 3 ids, but I want to show the name corresponding to those ids instead, this is the query I've got so far:

SELECT A.name as C1, B.name as C2, P1.name as PN
FROM country A
JOIN country_comm CC1 ON A.id=CC1.exporter_id
JOIN product P1 ON CC1.product_id=P1.id
JOIN country B JOIN country_comm CC2 ON B.id=CC2.importer_id
JOIN product P2 ON CC2.product_id=P2.id

Of course the result I get isn't what I want, this is what I get:

C1     |C2       |P1
Brazil |Argentina|Copper
Brazil |Argentina|Iron
Albania|Argentina|Stone
Brazil |Germany  |Copper
Brazil |Germany  |Iron
Albania|Germany  |Stone
Brazil |Argentina|Copper
Brazil |Argentina|Iron
Albania|Argentina|Stone

This is what I want:

C1     |C2       |P1
Brazil |Argentina|Copper
Brazil |Germany  |Iron
Albania|Argentina|Stone

Presumably, there is one row in country_comm for each product , with two columns referencing table country . If so, you would phrase the query as:

select c1.name as importer_country, c2.name as exporter_country, p.name as product_name 
from product p
inner join country_comm cc on cc.product_id = p.id
inner join country c1      on c1.id = cc.importer_id
inner join country c2      on c2.id = cc.exporter_id

In next approach you can select all rows from country_comm table and join dictionaries tables for translate ids into names like:

select 
    importer.name as importer_country, 
    exporter.name as exporter_country, 
    product.name as product_name 
from country_comm cc
join product           on product.id = cc.product_id
join country importer  on importer.id = cc.importer_id
join country exporter  on exporter.id = cc.exporter_id
;

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