如何从与另一个表有一对多关系的表中选择特定列?

时间:2018-04-11 17:56:23

标签: php mysql sql pdo

我有2个表具有一对多的关系(用户和位置),每个用户都有一个位置,但位置可能有很多用户。

users表中,有一个名为location_id的列与id表中名为locations的列相关。

locations.id - > users.location_id。

所以当我想要获取所有users及其locations时,我会使用以下代码:

//Select all the users.
$stmt = $pdo->prepare('SELECT * 
                        FROM users 
                            JOIN locations ON users.location_id = locations.id ');
$stmt->execute();
$values = $stmt->fetchAll(); 

//Loop through the users.
foreach($values as $val){
    $userName = $val['name'];

    //Get The location_id from users table.
    $locationId = $val['location_id']; 

    //Select the location based on this location_id.  
    $st = $pdo->prepare('SELECT * from locations WHERE id = :zid');
    $st->execute(array('zid' => $locationId));
    $v = $st->fetch();
    $location =  $v['location'];
}

是否有更好的方法可以获得相同的结果?

1 个答案:

答案 0 :(得分:2)

就我所知,这会做同样的事情

//Select all the users.
$stmt = $pdo->prepare('SELECT * 
                        FROM users 
                            JOIN locations ON users.location_id = locations.id ');
$stmt->execute();
$values = $stmt->fetchAll(); 

//Loop through the users.
foreach($values as $val){
    $userName = $val['name'];

    //Get The location
    $location =  $val['location'];
}