我已经创建了“一个班轮”,也许它有点复杂,但另外没有必要使用存储过程或临时表。
减号是其中的一部分,select 1 union select 2 union select 3 union...
因为我们需要为一个人创建尽可能多的行。
最后where id1 = 3
是你的参数。
create table users (id integer, group_id varchar(100));
insert into users
select 1, '1;2;3' union
select 2, '1;2;3;4' union
select 3, '1;2;3;6' union
select 4, '1;2;6';
select id2 as user_id
from (
select u1.id as id1, u2.id as id2, count(*) as qty
from (
select distinct id, group_id, substring_index(substring_index(group_id, ';', t.n), ';', -1) as g_id
from users
cross join (
select @i := @i + 1 as n from (select @i:=0) t0,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t1,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t2
) as t
) as u1
join users u2 on find_in_set(u1.g_id, replace(u2.group_id, ';', ',')) > 0
group by u1.id, u2.id
) as t
join (
select id, group_id, length(group_id) - length(replace(group_id, ';', '')) + 1 as groups_count
from users
) as g on t.id2 = g.id and g.groups_count <= t.qty
where id1 = 3;
SQL Fiddle 上的实时示例。
如果您需要超过 100 个组(每人),请添加另一行(使用不同的别名):
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) txxxx
我已经检查过了,它接缝没问题:
- 为 1 返回 1
- 对于 2 返回 1, 2
- 对于 3,返回 1、3、4
- 为 4 返回 4