新的mysql,感谢任何帮助。
我有三个表:organizations
,locations
和shows
。我想使用organizations
和locations
中自动增量分配的主键作为shows
中的外键。当我输入此表的值时,代码mysql如何自动拉取shows
的外键?或者,根据自动递增的主键自动分配的内容,当我在shows
中输入每行的值时,手动分配是最佳做法吗?
以下是我创建所有三个表的方法,organizations
和locations
都已插入所有条目(因此通过自动增量分配主键):
组织
CREATE TABLE organizations(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name VARCHAR(64) NOT NULL,
sex CHAR(1) NOT NULL,
start_year YEAR NOT NULL,
end_year YEAR NOT NULL,
notes LONGTEXT,
PRIMARY KEY (id)
);
地点
CREATE TABLE locations (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name VARCHAR(64) NOT NULL,
address_name VARCHAR(64) NOT NULL,
address_lat FLOAT(10,6) NOT NULL,
address_long FLOAT(10,6) NOT NULL,
type VARCHAR(64) NOT NULL,
notes LONGTEXT,
PRIMARY KEY (id)
);
:显示
CREATE TABLE shows (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
organization_id MEDIUMINT NOT NULL,
location_id MEDIUMINT NOT NULL,
date DATE NOT NULL,
cost DECIMAL (2,2),
money_raised DECIMAL (6,2),
charity VARCHAR(64),
audience_size MEDIUMINT,
band VARCHAR(64),
blackface CHAR(1),
drag CHAR(1),
notes LONGTEXT,
PRIMARY KEY (id)
);
ALTER TABLE shows
ADD CONSTRAINT FK1_shows
FOREIGN KEY (organization_id) REFERENCES organizations(id)
ON UPDATE CASCADE
ON DELETE CASCADE;
ALTER TABLE shows
ADD CONSTRAINT FK2_shows
FOREIGN KEY (location_id) REFERENCES organizations(id)
ON UPDATE CASCADE
ON DELETE CASCADE;
答案 0 :(得分:0)
您可以使用insert语句,根据名称值从其他表中选择 id 值,如下所示:
INSERT INTO shows (
organization_id,
location_id,
date
) VALUES (
(SELECT id FROM organizations WHERE name = 'my_org_name'),
(SELECT id FROM locations WHERE name = 'my_loc_name'),
'2016-05-01'
);
当然,您也会为其他一些列插入值。