简体   繁体   中英

MYSQL: select multiple records from other table for each row

I have 3 tables - users, items, and relations (each user have more than 1 item):

USERS:

user_id | user_name

1       | Alex
2       | John
3       | Louis

ITEMS:

item_id | item_name

1       | Item 1
2       | Item 2
3       | Item 3

RELATIONS:

item_id | user_id

1       | 1
2       | 1
1       | 2
3       | 2
2       | 3
3       | 3
3       | 1

etc..

So I need a query where I can get all users (that's easy) with all items for each user (it's more crazy).

So as a result I need something like this:

[1] => (
   'name' => Alex, 
   'items' => (
      [1] => (
         'name' => 'item 1'
      )
      [2] => (
         'name' => 'item 2'
      )
   )
)
[2] => (
   'name' => John, 
   'items' => (
      [1] => (
         'name' => 'item 1'
      )
      [2] => (
         'name' => 'item 3'
      )
   )
)

I've been playing with JOIN couple of hours but still can't get into it.

Thank you for any help!

To achieve a result like the one you want, you'll have to do some manipulation of your data in PHP because MySQL doesn't return multi-dimensional arrays. You can use joins to get the data you're after like this though:

SELECT
    users.user_name,
    items.item_name
FROM users
LEFT JOIN relations 
    ON relations.user_id = users.user_id
LEFT JOIN items 
    ON relations.item_id = items.item_id

This should return you results like this:

user_name | item_name
Alex        Item 1
Alex        Item 2
Alex        Item 3

etc. Then use PHP to group it up nicely:

$grouped = array();
foreach($your_database_results as $row) {
    $username = $row['user_name'];
    if(!array_key_exists($username, $grouped))
        $grouped[$username] = array();
    $grouped[$username][] = $row['item_name'];
}

Then your print_r($grouped) should look similar your example (I've used the name as the array key instead of the first array entry with the values following - easy enough to convert).

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