[英]How to select specific column from a table that has one to many relationship with another table?
I have 2 tables that have one to many relationship (users & locations) , Each user has one location , But location could have many users. 我有2个表具有一对多关系(用户和位置),每个用户有一个位置,但是位置可以有许多用户。
In users
table there is a column called location_id
that is related to the column called id
in locations
table. 在
users
表中,有一个名为location_id
的列,与locations
表中名为id
的列相关。
locations.id -> users.location_id. location.id-> users.location_id。
So when I want to get all the users
and their locations
, I use this code: 因此,当我想获取所有
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'];
}
Is there is a better way for getting the same result? 有没有更好的方法来获得相同的结果?
this would do the same thing as far as i can tell 据我所知,这将做同样的事情
//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'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.