赞
踩
有两张表A,B,主表诡异的设计, 将用户表的id用逗号分隔做字段保存。
而现在想要看每个用户的信息,就得把id逗号拼接做拆分。
模拟了一张order表
模拟了一张order_user表
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
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。