简体   繁体   English

MYSQL:从其他表中为每行选择多个记录

[英]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): 我有3个表-用户,项目和关系(每个用户有1个以上的项目):

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. 我已经和JOIN玩了几个小时,但仍然无法进入。

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. 为了获得想要的结果,您将不得不在PHP中对数据进行一些操作,因为MySQL不会返回多维数组。 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: 等等。然后使用PHP很好地将其分组:

$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). 然后,您的print_r($grouped)应该类似于您的示例(我将名称用作数组键,而不是第一个数组条目,其值后面的内容-足够容易转换)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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