我有数据存储在数据库中,我正在根据slug字段进行选择。
在某些情况下,两个项目都有相同的slug,在这些情况下我想基本上做一个group by slug
虽然我仍然希望以某种方式返回两组数据,也许创建2行的子数组?
有没有办法做到这一点。如果我的解释不清楚,我可以尝试进一步解释。
答案 0 :(得分:1)
根据您的评论进行修改 -
如果您希望将值作为单独的列显示,则可以使用变量:
给出示例数据:
create table slugs
(
item varchar(20),
slug varchar(20)
);
insert into slugs values ('Item A','Slug A');
insert into slugs values ('Item B','Slug A');
insert into slugs values ('Item C','Slug B');
insert into slugs values ('Item D','Slug A');
insert into slugs values ('Item E','Slug A');
insert into slugs values ('Item F','Slug A');
insert into slugs values ('Item G','Slug A');
insert into slugs values ('Item H','Slug A');
执行命令
select slug,
min(if(rn=1,item,null)) as item_1,
min(if(rn=2,item,null)) as item_2,
min(if(rn=3,item,null)) as item_3,
min(if(rn=4,item,null)) as item_4,
min(if(rn=5,item,null)) as item_5,
min(if(rn=6,item,null)) as item_6,
min(if(rn=7,item,null)) as item_7
from(
select @rn:=case when @slug=slug then @rn+1 else 1 end as rn,
@slug:=slug as slug,
item
from slugs cross join (select @rn:=0,@slug:='') r
order by slug
) x
group by slug;
输出:
| slug | item_1 | item_2 | item_3 | item_4 | item_5 | item_6 | item_7 |
|--------|--------|--------|--------|--------|--------|--------|--------|
| Slug A | Item A | Item B | Item D | Item E | Item F | Item G | Item H |
| Slug B | Item C | (null) | (null) | (null) | (null) | (null) | (null) |
(为每个可能的项目添加一个IF,即如果给定的slug最多有10个项目,则再添加3个)
小提琴: http://sqlfiddle.com/#!9/f5832/4/0
或者,如果您不关心单独列中的值,则可以更简单地使用group_concat
:
select slug,
group_concat(item) as items
from slugs
group by slug;
输出:
| slug | items |
|--------|--------------------------------------------------|
| Slug A | Item A,Item B,Item D,Item E,Item F,Item G,Item H |
| Slug B | Item C |