所以我有一个多对多的关系数据库,现在我正处于建立数据库的阶段。
我正在使用mariadb,并且已阅读到在处理M:M时,最好有一个中间表来存储关系。我正在尝试这样做,但是我太笨了,以至于我无法找出创建列的正确语法?
CREATE TABLE doctor_hospitals (
doctor_id INT FOREIGN KEY (doctor_id) REFERENCES doctors(id),
hospital_id INT FOREIGN KEY (hospital_id) REFERENCES hospitals(id)
) ENGINE = InnoDB;
上面产生错误:
查询1错误:您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册以获取正确的语法,以在'FOREIGN KEY(doctor_id)附近使用引用doctors(id), 第2行的hospital_id INT FOREIGN KEY'
同时:
CREATE TABLE doctor_hospitals (
FOREIGN KEY (doctor_id) REFERENCES doctors(id),
FOREIGN KEY (hospital_id) REFERENCES hospitals(id)
) ENGINE = InnoDB;
产生错误:
查询1错误:一个表必须至少具有1列
这种排序很有道理。这是我要创建的内容:
CREATE TABLE doctors (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
userID VARCHAR(100) NOT NULL,
first_names VARCHAR(100) NOT NULL,
last_names VARCHAR(100) NOT NULL,
medical_number INT NOT NULL,
email VARCHAR(20) NOT NULL,
country VARCHAR(20) NOT NULL,
province VARCHAR(20) NOT NULL,
city VARCHAR(20)) ENGINE = InnoDB;
CREATE TABLE hospitals (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(150) NOT NULL,
address1 VARCHAR(75),
address2 VARCHAR(75),
phone_number INT,
country VARCHAR(15),
province VARCHAR(15),
city VARCHAR(20),
zip_code VARCHAR(15)) ENGINE = InnoDB;
CREATE TABLE doctor_hospitals (
doctor INT FOREIGN KEY (doctor_id) REFERENCES doctors(id),
hospital INT FOREIGN KEY (hospital_id) REFERENCES hospitals(id)
) ENGINE = InnoDB;
感谢您的帮助!
答案 0 :(得分:2)
FK是约束。您需要首先定义列。还需要为FK定义索引。
CREATE TABLE doctor_hospitals (
doctor_id INT UNSIGNED NOT NULL,
hospital_id INT UNSIGNED NOT NULL,
PRIMARY KEY (doctor_id,hospital_id),
KEY IX_doctor_hospitals_hospital_id(hospital_id),
CONSTRAINT FK_doctor_hospitals_hospitals FOREIGN KEY (hospital_id) REFERENCES hospitals(id),
CONSTRAINT FK_doctor_hospitals_doctors FOREIGN KEY (doctor_id) REFERENCES doctors(id)
) ENGINE = InnoDB;