MySQL加入4张桌子

MySQL joining 4 tables

我正在尝试加入 4 tables:

我的 table 是:


详细table信息:

  • 用户:ID、姓名、电子邮件和其他一些信息字段
    例如1, chatu rohra, chaturanga@example.com, 其他几个信息字段
  • 组:ID、姓名、电子邮件和一些其他信息字段
    例如1, SOME_GROUP_NAME some@email.com, 几个其他信息字段
  • users_groups: id, user_id, group_id.
    例如1, 1, 1
  • user_favorite_group: id, user_id, user_group_id.
    例如1, 1, 1

  • 我可以加入前三个 table(用户、组、users_groups),但不能加入 user_favorite_group。我的查询是:

    SELECT
    users.*,
    GROUP_CONCAT(DISTINCT groups.name ORDER BY groups.name ASC SEPARATOR ', ') as groups
    FROM users_groups
        INNER JOIN users ON users.id = users_groups.user_id
        INNER JOIN groups ON groups.id = users_organizations.organization_id
        WHERE users.id = 1;
    

    这给了我:
    users.id、users.name、users.email、组 1, chatu rohra, 一些@email.com, SOME_GROUP_NAME

    我想看到的是..假设组中有更多组table:
    1, chatu rohra, 一些@email.com, "AND_ANOTHER, SOME_GROUP_NAME, SOME_OTHER_GROUP", "SOME_OTHER_GROUP"

    第 4 个字段是我所属的组的列表,第 5 个字段是我最喜欢的组。

    任何关于名字的建议 tables,性能也会很好。

    谢谢。

    加入 user_favorite_group table 的最简单方法是将其作为附加 LEFT JOIN 添加到 user_id 以获得 用户 关系的一部分,然后在 groups table 中添加一个额外的 INNER JOIN 以获得组名。尝试从现有 INNER JOINgroups.

    获取组名可能不起作用
    SELECT
      users.*,
      GROUP_CONCAT(DISTINCT groups.name ORDER BY groups.name ASC SEPARATOR ', ') as groups,
      gfav.name AS favorite_group
    FROM users_groups
        INNER JOIN users ON users.id = users_groups.user_id
        INNER JOIN groups ON groups.id = users_organizations.organization_id
        -- Join user to user_favorite_group
        -- Using LEFT JOIN in case the user has no favorite, it will return a NULL.
        LEFT JOIN `user_favorite_group` ON users.id = user_favorite_group.user_id
        -- Join that to `groups` to get its group name
        INNER JOIN groups gfav ON user_favorite_group.user_group_id
    WHERE users.id = 1
    -- MySQL will allow only users.id in the GROUP BY (or none at all)
    -- but know that this isn't entirely portable.
    GROUP BY users.id
    

    再看你的列名,我可能理解错了关系。如果 user_favorite_group.user_group_id 实际上指向 FOREIGN KEYuser_groups.id 而不是像我在这里表达的 groups.id ,你实际上需要另一个额外的连接:

    FROM users_groups
        INNER JOIN users ON users.id = users_groups.user_id
        INNER JOIN groups ON groups.id = users_organizations.organization_id
        -- Join user to user_favorite_group
        -- Using LEFT JOIN in case the user has no favorite, it will return a NULL.
        LEFT JOIN `user_favorite_group` ON users.id = user_favorite_group.user_id
        -- Join through `user_groups` to get the relationship
        INNER JOIN user_groups ugfav ON user_favorite_group.user_group_id = ugfav.id
        -- Join ultimlately back to `groups` to get the group name.
        INNER JOIN groups gfav ON ugfav.group_id = .gfav.id