[英]join three tables by SQL and Php
我在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
);
現在,我要獲取指定用戶加入的所有組,並且該組的所有成員都帶有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']
]
]
]
(由id確定的指定用戶, u_id
是外鍵T_Users
, g_id
是外鍵T_Groups
)
如果您只想要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;
在這里?
用於具有名稱的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.