[英]Optimizing the mysql join when a lot of repetitive data in the column to join on
[英]Join on piped column data
我必須使用一個MySQL數據庫,其中某些列將不同的ID保存在一列中,並用管道字符分隔。 例如:
用戶表:
id | username | groups
1 | user1 | 1|2|3|5
組ID對應於組。 它顯示了用戶所在的Groups
。因此,還有一個“ Groups
表:
組表:
id | groupname
1 | group1
2 | group2
3 | group3
4 | group4
5 | group5
我想要做的是選擇一個用戶,然后選擇所有的groupnames
,這個用戶被放置在,像一個JOIN
。 對於user1
這是除 group4
之外的 所有組。
如果將組保存在另一個名為user_groups
表中,這顯然會更容易:
user_groups表:
fk_user_id | fk_group_id
1 | 1
1 | 2
1 | 3
1 | 5
但是,不幸的是我無法更改數據庫架構,因為整個系統已經以此為基礎。
我想知道在單個查詢中選擇用戶時是否有一種獲取所有組名的聰明方法。 例如,結果可能看起來像這樣:
id | username | groups | groupnames
1 | user1 | 1|2|3|5 | group1|group2|group3|group5
是否可以以某種方式在MySQL的一次查詢中執行類似的操作?
在MySQL中,可以將find_in_set()
用於這種類型的find_in_set()
:
select *
from user u join
groups g
on find_in_set(g.groupname, u.groups) > 0;
在MySQL或其他數據庫中,您也可以使用like
:
select *
from user u join
groups g
on concat('|', g.groupname, '|') like concat('%|', u.groups, '|%');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.