简体   繁体   中英

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.

In users table there is a column called location_id that is related to the column called id in locations table.

locations.id -> users.location_id.

So when I want to get all the users and their locations , I use this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM