[英]How can I connect data from two different tables in mysql (LEFT JOIN)?
我想從mySQL數據庫連接兩個不同表的數據。 這運作良好,但我有一個小問題:
$sql = "SELECT * FROM person h LEFT JOIN animals o ON ( o.name = h.name);" ;
表person
:
| id | name | age |
|----|------|-----|
| 1 | fred | 9 |
| 2 | tom | 8 |
| 3 | kim | 6 |
餐桌animals
:
| id | name | animal |
|----|------|--------|
| a | fred | cat |
| b | tom | frog |
| c | kim | dog |
所以對於這個循環...
foreach ($pdo->query($sql) as $row) {
echo "$row['id']";
echo "$row['animal']";
}
...我得到結果:
| a | cat |
| b | frog |
| c | dog |
但我實際需要的結果是
| 1 | cat |
| 2 | frog |
| 3 | dog |
因此,我需要animals
的關聯數據,但仍然保留person
的id
。
只需更改返回值
"SELECT person.id id, animals.animal animal FROM person h LEFT JOIN animals o ON ( o.name = h.name);"
這將返回您想要的2個值。 如果需要更多列,只需添加它們。
您需要從person
而非animals
那里獲得ID字段。
獲取單獨的ID field
。
$sql = "SELECT *, h.id as pid FROM person h
LEFT JOIN animals o ON o.name = h.name";
PHP的變化:
foreach ($pdo->query($sql) as $row) {
echo $row['pid'];
echo $row['animal'];
}
如果使用MySQL: ALIASES
查詢,請使用MySQL: ALIASES
表名稱的別名
$sql = "SELECT *, pr.id as personId FROM person pr LEFT JOIN animals al ON al.name = pr.name";
foreach ($pdo->query($sql) as $row) {
echo "$row['personId']";
echo "$row['animal']";
}
由於id
在此處以及PHP array having same key than last will overwrite the first
ambiguous
字段中, array having same key than last will overwrite the first
因此您需要像
SELECT h.id as pid,* FROM person h
LEFT JOIN animals o ON o.name = h.name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.