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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)