如何在MySQL中加入非规范化表?

时间:2017-03-07 15:48:43

标签: mysql join

我有一张不同people的表格。我想将它们连接到我的house

house表:

+-------+---------+---------+---------+
| house | person1 | person2 | person3 |
+-------+---------+---------+---------+
|     1 |       2 |       4 |       1 |
|     2 |       3 |       1 |       2 |
+-------+---------+---------+---------+

people表:

+----+------+
| id | name |
+----+------+
|  1 | fred |
|  2 | john |
|  3 | leo  |
|  4 | tom  |
+----+------+

这样的事情可能吗?

$pdo = $db->query('
 SELECT *
 FROM house
 LEFT JOIN people
 ON house.person1=people.id
 AND house.person2=people.id
 ;');
 while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    echo "Person 1 = ".$row['name'];
    echo "Person 2 = ".$row['name'];
 }

3 个答案:

答案 0 :(得分:3)

即将结束,您需要ORIN()代替AND

SELECT *
FROM house h
LEFT JOIN people p ON p.id IN(h.person1,h.person2,h.person3)

但我相信,更好的方法是改变评论中提出的表格设计。在这种情况下,您只需要:

SELECT *
FROM house h
LEFT JOIN people p ON h.person = p.id

答案 1 :(得分:3)

你应该在表3上使用自己加入3个别名

  $pdo = $db->query('
   SELECT *, people1.name  as name1, people2.name  as name2, people3.name  as name3
   FROM house
   LEFT JOIN people as people1 ON house.person1=people1.id
   LEFT JOIN people as people2 ON house.person2=people2.id
   LEFT JOIN people as people3 ON house.person3=people3.id
   ;');
   while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
      echo "Person 1 = ".$row['name1'];
      echo "Person 2 = ".$row['name2'];
      echo "Person 3 = ".$row['name3'];
   }

答案 2 :(得分:1)

如果你需要知道每个房子里3个人的名字,你可以使用这个

$pdo = $db->query('
select A.house, B.name as person1, C.name as person2, D.name as person3
from house A join people B on (A.person1=B.id) left join people C on   (A.person2=C.id) join people D on (A.person3=D.id)
;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
  echo "house = ".$row['house']; 
  echo "Person 1 = ".$row['person1'];
  echo "Person 2 = ".$row['person2'];
  echo "Person 2 = ".$row['person3'];
}