通过同一个表中的不同ID连接两行

时间:2017-08-23 13:19:56

标签: sql

我想通过同一个表中的不同ID连接两行。

Fruit table:
name:    from_id:   to_id:
Apple    Spain      Italy

Country table:
id:      packaging_type:    packaging_quantity:
Italy    wood box           12
Spain    paper box          18

我想得到这张表:

Spain paper box 18 Italy wood box 12

我尝试过这样的事情:

SELECT a.packaging_type, a.packaging_quantity, b.packaging_type, b.packaging_quantity 
FROM fruit
    inner join country a on a.country.id = fruit.from_id
    inner join country b on b.country.id = fruit.to_id
WHERE fruit.name = 'Apple';

但我收到了一个错误:

ORA-00904: "A"."COUNTRY"."ID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 2 Column: 12

3 个答案:

答案 0 :(得分:3)

您正在INNER JOIN中为县表设置别名。您无需在别名as后重复表名称。只需使用a.id代替a.county.id

SELECT a.packaging_type, a.packaging_quantity, b.packaging_type, b.packaging_quantity 
FROM fruit
INNER JOIN country a ON a.id = fruit.from_id
INNER JOIN country s ON b.id = fruit.to_id
WHERE fruit.NAME = 'Apple';

此外,如果想要保持一致,可以使用fruit表的别名。

SELECT a.packaging_type, a.packaging_quantity, b.packaging_type, b.packaging_quantity 
FROM fruit f
INNER JOIN country a ON a.id = f.from_id
INNER JOIN country s ON b.id = f.to_id
WHERE f.NAME = 'Apple';

答案 1 :(得分:1)

您只需使用a.id,而不是a.country.id

因此,您的查询将是:

SELECT a.packaging_type, a.packaging_quantity, b.packaging_type, b.packaging_quantity 
FROM fruit
    inner join country a on a.id = fruit.from_id
    inner join country s on b.id = fruit.to_id
WHERE fruit.name = 'Apple';

答案 2 :(得分:1)

a.country.id应为a.id

b.country.id应为b.id