SQLite3中列名不明确,但不明确难以避免

vc9ivgsu  于 2023-03-08  发布在  SQLite
关注(0)|答案(1)|浏览(138)

Linux Arch上的SQLite3。一个国家名称表,每个版本的FIFA世界杯主办国和冠军列表将通过外键引用该表。理想情况下,我将把它扩展到多个字段,如:亚军、铜牌获得者、第四名等。具有国家列表的表保持相同,为了说明的目的,另一个表将仅从国家列表中获得数据两次,但是数据库应当能够从国家列表中对国家排序13、16、24和32次。
国家列表创建如下:

CREATE TABLE countries (countries_id integer primary key autoincrement, country text);

世界杯版本表创建如下:

CREATE TABLE editions (
    edition_id integer primary key autoincrement,
    year integer not null,
    host integer not null,
    champion integer not null,
    foreign key (host) references countries (countries_id),
    foreign key (champion) references countries (countries_id)
);

只需填写国家列表中的四个条目(最终应包括200多个条目):

INSERT INTO countries (country) VALUES('Uruguay');                                                   
INSERT INTO countries (country) VALUES('Italy');                                                     
INSERT INTO countries (country) VALUES('France');                                                    
INSERT INTO countries (country) VALUES('Brazil');

仅仅是前四届的比赛:

INSERT INTO editions (year,host,champion) VALUES(1930,1,1);                                          
INSERT INTO editions (year,host,champion) VALUES(1934,2,2);                                          
insert into editions (year, host, champion) values (1938,3,2);                                       
insert into editions (year, host, champion) values (1950,4,1);

此查询适用于:

select editions.year, countries.country
from editions inner join countries on countries.countries_id=editions.host;

到目前为止一切顺利,但我得到了“解析错误:列名不明确:countries.country“只要我尝试执行以下SELECT语句:

select editions.year, countries.country as host_c, countries.country as champion_c
from
  editions
  inner join countries on countries.countries_id=editions.host
  inner join countries on countries.countries_id=editions.champion;

在某种程度上,这对我来说是很自然的,因为我确实对表countries查询了两次,但是我仍然希望能够执行这样的查询。
SQLite的最终结果应该是显示一个三列表,显示世界杯的年份、主办国的名称和赢得该版本的国家,除了查询countries.country两次之外,我没有其他想法。
正确的SELECT语句应该是什么,这样我就可以有版本的年份,主办国和冠军国,只使用一个有国家名称的表?非常感谢。

waxmsbnn

waxmsbnn1#

对表名使用别名

select editions.year, H.country as host_c, C.country as champion_c
from
  editions
  inner join countries H
    on H.countries_id = editions.host
  inner join countries C
    on C.countries_id = editions.champion;

您还可以使用其他表的别名来缩短SQL

select E.year, H.country as host_c, C.country as champion_c
from
  editions E
  inner join countries H
    on H.countries_id = E.host
  inner join countries C
    on C.countries_id = E.champion;

别名也可以通过可选关键字AS引入:

...
from
  editions AS E

相关问题