【问题标题】:join three tables by SQL and Php通过 SQL 和 PHP 连接三个表
【发布时间】:2018-08-04 15:23:21
【问题描述】:

我在 mysql 数据库中有这 3 个表(我也不知道它是否完全标准化?

或者有没有更好的方法来设计这个表来获取这个查询?)

create table T_Users(
     id int
     name varchar (50)
     picture varchar (11)
);
create table T_Groups(
     id int
     name varchar (50)
     admin_id int
);
create table T_Group_Users(
     u_id int
     g_id int
);

现在我想获取指定用户加入的所有组,以及该组的所有成员及其详细信息(名称和图片) 并通过 Php 创建一个这样的数组(这是一个例子):

$groups = [ // Groups user by id = 1 joined 'em
        [
            'id' => 1,
            'name' => 'G_1',
            'member' => [
                ['name' => 'R', 'picture'=>''],
                ['name' => 'S', 'picture'=>'14.jpg'],
                ['name' => 'X', 'picture'=>'']
            ]
        ],
        [
            'id' => 5,
            'name' => 'G_3',
            'member' => [
                ['name' => 'T', 'picture'=>'11.jpg'],
                ['name' => 'S', 'picture'=>'14.jpg']
            ]
        ]
    ]

(指定用户由id确定,u_id为外键T_Usersg_id为外键T_Groups

【问题讨论】:

  • @emineminems 我不明白我应该把 id 放在哪里?这个查询只返回false。表格不为空
  • 如果表不是空的,那么它应该给出具有适当id的结果。
  • @mohit-kumar 否 查询在T_Groups.g_id = T_Groups 中存在错误@ T_Groups 没有 g_id
  • 错字ON T_Groups.id = T_Group_Users.g_id

标签: php mysql sql arrays join


【解决方案1】:

如果你只想要 id,你可以这样做:

select g_id, group_concat(u_id)
from t_group_users gu
group by g_id
having sum(u_id = ?) > 0;

这会返回一行中的每个组,其中包含组中用户的 ID 列表。

如果您想要这些名称,请在相应的表格中添加join

编辑:

要获取名称和其他信息:

select g.id, g.name,
       group_concat(u.name, ':', u.picture)
from t_group_users gu join
     t_users u
     on gu.u_id = u.id join
     t_groups g
     on gu.g_id = g.id
group by g.id, g.name
having sum(u.name = ?) > 0;

这里的? 是有名字的参数。

【讨论】:

  • SELECT t_groups.*, member FROM t_groups Left JOIN t_group_users ON t_groups.id = t_group_users.g_id where t_group_users.u_id = 1 (SELECT t_users.* FROM t_users Left JOIN t_group_users ON t_group_users.g_id = t_groups.id) AS member 这不起作用,但我认为我想要的是这样的......
猜你喜欢
  • 1970-01-01
  • 2021-06-21
  • 2022-01-15
  • 2020-12-10
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多