有两张表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

————————————
发现还可以用find_in_set() 函数
该函数能将逗号分隔的字符串分解成set的形式
以用户的id在逗号分隔的id用户id表为查询条件
find_in_set(user.id, `order`.users)
select temp.*, user.user_name, user.email from
`order` temp left join order_user user on find_in_set(user.id, temp.users)
order by temp.id

博客围绕数据库表操作展开,主表设计将用户表id用逗号分隔保存。为查看每个用户信息,需拆分逗号拼接的id。通过模拟order表和order_user表,拆分id形成临时表并与用户表关联获取信息,还可按需用group by继续拼接,也提到用函数分解字符串。
5160

被折叠的 条评论
为什么被折叠?



