gpt4 book ai didi

php - 如何左连接来自同一个 mySQL 表的多个数据?

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:02 25 4
gpt4 key购买 nike

这是我的 table 位置:

+----+---------+------+--------+---------+
| id | teacher | cook | doctor | dentist |
+----+---------+------+--------+---------+
| 1 | 3 | 4 | 2 | 1 |
+----+---------+------+--------+---------+

这是我的表:

+----+-----------+--------+-----+
| id | firstname | name | age |
+----+-----------+--------+-----+
| 1 | Fred | Miller | 42 |
| 2 | Emily | Rose | 32 |
| 3 | Ben | Harper | 38 |
| 4 | Samanta | Jones | 35 |
+----+-----------+--------+-----+

mySQL数据库请求

$pdo = $db->query('
SELECT *, position.id AS id, people.id AS people_id
FROM position
LEFT JOIN people
ON position.teacher=people.id;
ON position.cook=people.id;
ON position.doctor=people.id;
ON position.dentist=people.id;
');

while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "The teacher is "$row['firstname']." ".$row['name'];
echo "The cook is "$row['firstname']." ".$row['name'];
echo "The doctor is "$row['firstname']." ".$row['name'];
echo "The dentist is "$row['firstname']." ".$row['name'];
}

我的结果是:

The teacher is Ben Harper
The cook is Ben Harper
The doctor is Ben Harper
The dentist is Ben Harper

我需要的结果:

The teacher is Ben Harper
The cook is Samanta Jones
The doctor is Emiliy Rose
The dentist is Fred Miller

最佳答案

如果你重组你的表格会更好。

+----+------------+| id | position   |       +----+------------||  1 |  teacher   ||  2 |  cook      ||  3 |  doctor    ||  4 |  dentist   |+----+------------++----+-----------+--------+-----+-------------+| id | firstname |  name  | age | position_id |+----+-----------+--------+-----+-------------+|  1 | Fred      | Miller |  42 |  4          ||  2 | Emily     | Rose   |  32 |  3          ||  3 | Ben       | Harper |  38 |  1          ||  4 | Samanta   | Jones  |  35 |  2          |+----+-----------+--------+-----+-------------+

Here you can have a foreign key reference on people.position_id and position.id.This way you can have many people with same position.

SELECT position.id id
, people.id people_id
, people.firstname
, people.name
FROM position
LEFT
JOIN people
ON people.position_id = position.id;

关于php - 如何左连接来自同一个 mySQL 表的多个数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42583873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com