我只是mysql的新手。我在购物车表格中有以下记录
id code
1 100
2 101
3 102
4 100
5 100
6 101
我的例外输出如下:-
id code serial_number
1 100 1
2 101 2
3 102 3
4 100 1
5 100 1
6 101 2
我想要属于同一组的相同序列号,即代码。谁能帮我怎么做?
答案 0 :(得分:0)
您的组以code = 100
开头定义。这有点棘手。在MySQL 8+中,您可以使用窗口函数来定义组,然后使用row_number()
来分配serial_number
:
select c.*,
row_number() over (partition by grp order by id) as serial_number
from (select c.*,
sum( code = 100 ) over (order by id) as grp
from carts c
) c;
这在MySQL的早期版本中要复杂得多。
您可以使用子查询来标识组:
select c.*,
(select count(*)
from carts c2
where c2.id <= c.id and c2.code = 100
) as grp
from carts c;
然后您可以使用变量获取所需的信息:
select c.*,
(@rn := if(@g = grp, @rn + 1,
if(@g := grp, 1, 1)
)
) as serial_number
from (select c.*,
(select count(*)
from carts c2
where c2.id <= c.id and c2.code = 100
) as grp
from carts c
order by grp, id
) c cross join
(select @g := -1, @rn := 0) params;
答案 1 :(得分:0)
根据您的示例,代码始终具有相同的序列号。那你得到什么?
这是非常简单的查询:
select id, code, code - 99 as serial_number
from mytable
order by id;