为什么无法连接 MySQL 中的表?
Why a can't connect my tables in MySQL?
运输table结构
我想像这样连接到另一个 table(我收到“1215 错误”):
CREATE TABLE goods_and_shippings (
good_id INT NOT NULL,
s_date DATE NOT NULL,
shipping_id INT NOT NULL,
PRIMARY KEY (good_id),
FOREIGN KEY (s_date) REFERENCES shippings(s_date)
)
连接的列具有与您所见相同的数据类型(DATE 和 NOT NULL)并且所有 table 都使用 InnoDB 引擎。但是我有这个片段并且它有效:
CREATE TABLE goods_and_shippings (
good_id INT NOT NULL,
s_date DATE NOT NULL,
shipping_id INT NOT NULL,
PRIMARY KEY (good_id),
FOREIGN KEY (shipping_id) REFERENCES shippings(shipping_id)
)
目前所有 table 都是空的。这是创建运输的查询:
CREATE TABLE shippings (
shipping_id INT NOT NULL,
s_date DATE NOT NULL,
driver_id INT NOT NULL,
start_place VARCHAR(50) NOT NULL,
end_place VARCHAR(50) NOT NULL,
car_id INT NOT NULL,
price DECIMAL(5,2) NOT NULL,
PRIMARY KEY (shipping_id, s_date)
)
这里是我之后使用的改变:
ALTER TABLE shippings ADD CONSTRAINT fk_car_id FOREIGN KEY (car_id) REFERENCES cars(car_id);
ALTER TABLE shippings ADD CONSTRAINT fk_driver_id FOREIGN KEY (driver_id) REFERENCES drivers(driver_id);
我的查询有什么问题?如何解决此问题并连接 goods_and_shippings.s_date 和 shippings.s_date?
一般来说,外键引用是指唯一键或主键。但是,如 documentation:
中所述,INNODB 放宽了此条件
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
因此,您可以对 shipping_id
进行外部引用,因为它是主键中的第一个键,但不是最新的。但是,我建议您设置外键关系以完成主键。而且,我通常在所有表中都有一个自动递增的主键,以促进这种关系。
运输table结构
CREATE TABLE goods_and_shippings (
good_id INT NOT NULL,
s_date DATE NOT NULL,
shipping_id INT NOT NULL,
PRIMARY KEY (good_id),
FOREIGN KEY (s_date) REFERENCES shippings(s_date)
)
连接的列具有与您所见相同的数据类型(DATE 和 NOT NULL)并且所有 table 都使用 InnoDB 引擎。但是我有这个片段并且它有效:
CREATE TABLE goods_and_shippings (
good_id INT NOT NULL,
s_date DATE NOT NULL,
shipping_id INT NOT NULL,
PRIMARY KEY (good_id),
FOREIGN KEY (shipping_id) REFERENCES shippings(shipping_id)
)
目前所有 table 都是空的。这是创建运输的查询:
CREATE TABLE shippings (
shipping_id INT NOT NULL,
s_date DATE NOT NULL,
driver_id INT NOT NULL,
start_place VARCHAR(50) NOT NULL,
end_place VARCHAR(50) NOT NULL,
car_id INT NOT NULL,
price DECIMAL(5,2) NOT NULL,
PRIMARY KEY (shipping_id, s_date)
)
这里是我之后使用的改变:
ALTER TABLE shippings ADD CONSTRAINT fk_car_id FOREIGN KEY (car_id) REFERENCES cars(car_id);
ALTER TABLE shippings ADD CONSTRAINT fk_driver_id FOREIGN KEY (driver_id) REFERENCES drivers(driver_id);
我的查询有什么问题?如何解决此问题并连接 goods_and_shippings.s_date 和 shippings.s_date?
一般来说,外键引用是指唯一键或主键。但是,如 documentation:
中所述,INNODB 放宽了此条件InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
因此,您可以对 shipping_id
进行外部引用,因为它是主键中的第一个键,但不是最新的。但是,我建议您设置外键关系以完成主键。而且,我通常在所有表中都有一个自动递增的主键,以促进这种关系。