需要帮助合并三个表的外键
Need help in merging three tables foreign keys
我创建了三个这样的表,
1.
CREATE TABLE person (
id int NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
age int,
PRIMARY KEY (id)
);
2.
CREATE TABLE address (
id int NOT NULL AUTO_INCREMENT,
city varchar(50) NOT NULL,
post_code int NOT NULL,
person_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (person_id) REFERENCES person(id)
);
3
CREATE TABLE subjects (
id int NOT NULL AUTO_INCREMENT,
subjects_s varchar(50) NOT NULL,
address_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (address_id) REFERENCES address(id)
);
现在在表格中我有一些这样的信息:
人
+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | Sohan | 17 |
| 2 | Farhan | 18 |
+----+--------+------+
地址
+----+-------+-----------+-----------+
| id | city | post_code | person_id |
+----+-------+-----------+-----------+
| 1 | Tongi | 1711 | 1 |
| 2 | Dhaka | 1230 | 2 |
+----+-------+-----------+-----------+
学科
+----+--------------------+------------+
| id | subjects_s | address_id |
+----+--------------------+------------+
| 1 | Accounting Finance | 1 |
| 2 | Physics Math | 2 |
+----+--------------------+------------+
现在我想把所有这些数据一起展示。我怎样才能做到这一点?请帮忙!
您应该能够使用 SQL join 语句来组合这些。
语法在MySQL join documentation中有详细说明。
对于您的表,您的查询应如下所示:
SELECT person.*, address.*, subjects.*
FROM person
JOIN address ON person.id = address.person_id
JOIN subjects ON address.id = subjects.address_id
请记住,此示例使用内部联接,根据您表中的数据,这可能不是正确的联接类型。我建议阅读上面链接的文档以获得进一步的指导。
我创建了三个这样的表,
1.
CREATE TABLE person (
id int NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
age int,
PRIMARY KEY (id)
);
2.
CREATE TABLE address (
id int NOT NULL AUTO_INCREMENT,
city varchar(50) NOT NULL,
post_code int NOT NULL,
person_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (person_id) REFERENCES person(id)
);
3
CREATE TABLE subjects (
id int NOT NULL AUTO_INCREMENT,
subjects_s varchar(50) NOT NULL,
address_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (address_id) REFERENCES address(id)
);
现在在表格中我有一些这样的信息:
人
+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | Sohan | 17 |
| 2 | Farhan | 18 |
+----+--------+------+
地址
+----+-------+-----------+-----------+
| id | city | post_code | person_id |
+----+-------+-----------+-----------+
| 1 | Tongi | 1711 | 1 |
| 2 | Dhaka | 1230 | 2 |
+----+-------+-----------+-----------+
学科
+----+--------------------+------------+
| id | subjects_s | address_id |
+----+--------------------+------------+
| 1 | Accounting Finance | 1 |
| 2 | Physics Math | 2 |
+----+--------------------+------------+
现在我想把所有这些数据一起展示。我怎样才能做到这一点?请帮忙!
您应该能够使用 SQL join 语句来组合这些。
语法在MySQL join documentation中有详细说明。
对于您的表,您的查询应如下所示:
SELECT person.*, address.*, subjects.*
FROM person
JOIN address ON person.id = address.person_id
JOIN subjects ON address.id = subjects.address_id
请记住,此示例使用内部联接,根据您表中的数据,这可能不是正确的联接类型。我建议阅读上面链接的文档以获得进一步的指导。