donglv9116 2014-01-18 15:23
浏览 6
已采纳

创建一个干净的HABTM查询

i've been working to try and getting a clean HABTM query for MySQL

i have the following tables

auth_users

id: 1,name: test

auth_groups_users

user_id: 1,group_id: 1

user_id: 1,group_id: 2

auth_groups

id: 1,name: default_group

id: 2,name: another_group

I am pulling a user and inside the results i would like to get the group(s) as well.

The question is how do i join it properly... do i perform a left join... or regular.. do i join the link table first and then with what conditions? then what is next?

Thanks, please let me know if you need more info.

my start...

"SELECT * FROM auth_users AS User LEFT JOIN auth_groups_users ON (auth_groups_users.user_id = User.id) LEFT JOIN auth_groups AS Group ON (Group.id = auth_groups_users.group_id) WHERE User.id='1';"

is this correct/proper?

then i also want to group the groups into it's own result within the user.. not multiple results for the same user...

so i would like my result to be:

 array(
     'id' => 1,
     'name' => 'test',
     'Groups' => array(
           0 => array(
                'id' => 1,
                'name' => 'default_group'
           ),
           1 => array(
                'id' => 2,
                'name' => 'another_group'
           )
      )
 ) 
  • 写回答

1条回答 默认 最新

  • douyi9447 2014-01-18 15:43
    关注

    Forget about HABTM, those academic things are a sort of garbage in real life application, though you might require to answer this question in the future (or maybe right now).

    So let me clarify a bit, you have these tables

    users    group_users    groups
    -----    -----------    ------
    id       user_id        id
    name     group_id       name
    

    So basically what you want to do is to SELECT users and have their groups listed with them, am I right ?

    So the right query would be

    SELECT users.name, groups.name
    FROM users
    INNER JOIN groups_users ON users.id = group_users.user_id
    INNER JOIN groups ON groups.id = group_users.group_id
    

    This however will list ONLY the users who have a group, if you want to select also those who haven't, you should perform a left join instead of a inner join (the first one).

    I can't think of a really straight way to obtain what you want since a database will always return a set of rows. You have two ways to achieve what you want

    1. Use MySQl's GROUP_CONCAT
    2. Implement your own way through PHP (which isn't a big deal)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程