我有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'];
}
是否有更好的方法可以获得相同的结果?
答案 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'];
}