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

f45qwnt8  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(344)

我有两个具有一对多关系(用户和位置)的表,每个用户有一个位置,但位置可以有多个用户。
users 表中有一列名为 location_id 与名为 idlocations table。
locations.id->users.location\u 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'];
}

有没有更好的方法得到同样的结果?

oo7oh9g9

oo7oh9g91#

据我所知,这也会起同样的作用

//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'];
}

相关问题