[英]join three tables by SQL and Php
I have these 3 tables in mysql database (also i didn't know it's completely normalized or not? 我在mysql数据库中有这3个表(也是我不知道它是否已完全规范化?
or is there any better way to design this tables to get this query?) 还是有更好的方法来设计此表以获取此查询?)
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
);
Now I Want to get all of groups that a specified user joined, with all of members of this groups with them detail(name and picture) And create an array like this by Php (this is an example): 现在,我要获取指定用户加入的所有组,并且该组的所有成员都带有detail(名称和图片),并由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']
]
]
]
(specified user determined by id, u_id
is foreign key T_Users
And g_id
is foreign key T_Groups
) (由id确定的指定用户, u_id
是外键T_Users
, g_id
是外键T_Groups
)
If you just want ids, you can do: 如果您只想要ID,可以执行以下操作:
select g_id, group_concat(u_id)
from t_group_users gu
group by g_id
having sum(u_id = ?) > 0;
This returns each group on a row with a list of the ids of the users in the group. 这将返回一行中的每个组,并列出该组中用户的ID。
If you want the names, you an join
in the appropriate tables. 如果需要名称,则可以join
适当的表中。
EDIT: 编辑:
To get the names and other information: 要获取名称和其他信息:
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;
Here ?
在这里?
is for the parameter that has the name. 用于具有名称的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.