mysql拆分用逗號拼接的欄位做關聯
阿新 • • 發佈:2020-12-21
有兩張表A,B,主表詭異的設計, 將使用者表的id用逗號分隔做欄位儲存。
而現在想要看每個使用者的資訊,就得把id逗號拼接做拆分。
模擬了一張order表
模擬了一張order_user表
- 把逗號拼接的id做拆分做一張臨時表出來
select a.ID, substring_index(substring_index(a.users, ',', b.help_topic_id + 1), ',', -1) users
from `order` a join
mysql.help_topic b
on b.help_topic_id < (length(a.users) - length(replace(a.users, ',', '')) + 1)
order by a.ID
- 拆分後的臨時表和使用者表做關聯 獲取使用者資訊
select temp.*, user.user_name, user.email
from (
select a.ID, substring_index(substring_index(a.users, ',', b.help_topic_id + 1), ',', -1) users
from `order` a
join
mysql.help_topic b
on b.help_topic_id < (length(a.users) - length(replace(a.users, ',', '')) + 1)
order by a.ID
) temp left join order_user user on temp.users = user.id
order by temp.id
- 或者用group by ,繼續使用逗號拼接成一個欄位(具體看需求)
select temp.id, group_concat(temp.users), group_concat( user.user_name) user_name, group_concat(user.email) email
from (
select a.ID, substring_index(substring_index(a.users, ',', b.help_topic_id + 1), ',', -1) users
from `order` a
join
mysql.help_topic b
on b.help_topic_id < (length(a.users) - length(replace(a.users, ',', '')) + 1)
order by a.ID
) temp left join order_user user on temp.users = user.id
group by temp.id
order by temp.id