Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为mysql中的记录组提供相同的序列号_Mysql_Sql - Fatal编程技术网

如何为mysql中的记录组提供相同的序列号

如何为mysql中的记录组提供相同的序列号,mysql,sql,Mysql,Sql,我只是mysql的新手。我在carts表中有如下记录 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

我只是mysql的新手。我在carts表中有如下记录

 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

我想要属于同一组的相同序列号,即代码。有人能帮我怎么做吗?

您的组是从code=100开始定义的。这有点棘手。在MySQL 8+中,您可以使用窗口函数定义组,然后使用行号来分配序列号:

这在早期版本的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;

根据您的示例,代码的序列号始终相同。那么你得到了什么

下面是一个非常简单的查询:

select id, code, code - 99 as serial_number
from mytable
order by id;

继续试试看。这是一个很有趣的问题。答案并非微不足道。OP本可以更好地解释它,但是组是从code=100开始定义的,因此解决方案并不简单。您对序列号的要求是什么?由于序列号和代码之间显然存在1:1的关系,有什么理由反对使用代码本身作为序列号呢?我投了反对票,因为我的问题被忽略了。库纳尔没有回答,而是再次提出了几乎相同的问题,当然也出现了相同的问题:谁否决了这一点:请解释原因。每个代码都有一个序列号。我的想法完全一样,对于OPs数据序列号=代码-99。谁需要这些复杂的窗口功能@ThorstenKettner我的代码是16。为了更好地理解,我只是举了个例子。没有答案对我有效你在请求评论中看到我的问题了吗?您对序列号的要求是什么。。。请回答他们。为什么你给静态值100,而我的代码不像100开头,它在长字母中包含16个单词。所以这可能行不通
select id, code, code - 99 as serial_number
from mytable
order by id;