2017-08-13 36 views
1

如何基於來自PHP數據庫循環的兩個表中的匹配值提取數據?使用PHP PDO匹配來自MySQL數據庫中兩個表的數據並提取

在TABLE_X我列ZIPCODE和table_y我有ZIPCODE和STREETCODE這樣的:

+-----+---------+ +---------+------------+ 
| id | zipcode | | zipcode | streetcode | 
+---------------+ +---------+------------+ 
| 01 | 1234001 | | 1111001 |  123 | 
+---------------+ +---------+------------+ 
| 02 | 1234002 | | 1234001 |  456 | 
+---------------+ +---------+------------+ 
table_x   table_y 

我想提取與table_y匹配streetcode TABLE_X每一行,但我不知道哪join使用,如果我應該用代替while循環來實現我的目標。

$sql = 'SELECT * FROM table_x ORDER BY id'; 
    foreach ($db->query($sql) as $row) {     
     echo $row['zipcode'] . "<br>"; 
     // select from other table 
    } 

最終,輸出每一行與它旁邊的streetcode的郵政編碼..

回答

2

使用NATURAL JOIN,如果相關的表具有相同的列名zipcode和列是相同的數據類型。

SELECT * 
FROM table_x 
NATURAL JOIN table_y 

或者對zipcode

SELECT * 
FROM table_x 
INNER JOIN table_y 
ON table_x.zipcode=table_y.zipcode 
1

您可以使用連接查詢使用INNER JOIN

$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass); 
//replace table_x, y with your table names 
$sql = "SELECT table_x.zipcode, table_y.streetcode 
FROM table_x 
INNER JOIN table_y ON table_x.zipcode=table_y.zipcode"; 
$stmt = $dbh->prepare($sql); 
if ($stmt->execute()) { 
    while ($row = $stmt->fetch()) { 
     print_r($row); 
    } 
} 
相關問題