簡體   English   中英

如何連接來自mysql中兩個不同表的數據(LEFT JOIN)?

[英]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的關聯數據,但仍然保留personid

只需更改返回值

"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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM