[英]How can I populate my FK column in one table with the FK from another table?
I have got a football world cup database. 我有一个足球世界杯数据库。 These are the two important table I'm working on right now:
这是我正在研究的两个重要表格:
CREATE TABLE Countries(
Cid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE
);
CREATE TABLE Clubs(
Ncid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE,
Cid INT REFERENCES Countries NOT NULL
);
So I added a column 'country' in the clubs table which represents the country the club is in. The problem now is I need to populate the cid
column of the clubs table with the cid
that matches the country in the countries table. 所以我在俱乐部表格中添加了一个列“国家”,代表俱乐部所在的国家。现在的问题是我需要填写俱乐部表的
cid
列,其中cid
与国家/地区表中的国家/地区相匹配。
I have tried this and it didn't work: 我试过这个并没有用:
ALTER TABLE clubs ADD COLUMN country VARCHAR(255)
INSERT INTO clubs(name, country)
SELECT DISTINCT club_name, club_country
FROM tempsquads; //this loads the data from a temporary tabe into my table
INSERT INTO clubs(cid)
SELECT cid
FROM countries
WHERE clubs.country = countries.name;
Has anyone an idea of how I can perform such a query? 有谁知道如何执行这样的查询?
In your INSERT, link tempsquads to country: 在您的INSERT中,将tempsquads链接到country:
INSERT INTO CLUBS(name, cid)
(SELECT t.club_name, c.cid
FROM tempsquads t
INNER JOIN COUNTRIES c ON t.club_country=c.name)
Don't add the country name field to the clubs table--you will link on id when you need the name. 不要将国家/地区名称字段添加到俱乐部表格 - 当您需要名称时,您将链接到ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.