如何检查MySQL中的前一条记录?

时间:2015-11-16 10:11:04

标签: mysql sql optimization

+----+--------+-------------+
| ID |  Name  |  Category   |
+----+--------+-------------+
|  1 | Cat    | Animal      |
|  2 | Loin   | Animal      |
|  3 | Dog    | Animal      |
|  4 | Red    | Color       |
|  5 | Hen    | Bird        |
|  6 | Parrot | Bird        |
+----+--------+-------------+
  

我想要类别明智的序列号。这意味着输出

+----+--------+----------+--------+
| ID |  Name  | Category | Count  |
+----+--------+----------+--------+
|  1 | Cat    | Animal   |      1 |
|  2 | Loin   | Animal   |      2 |
|  3 | Dog    | Animal   |      3 |
|  4 | Red    | Color    |      1 |
|  5 | Hen    | Bird     |      1 |
|  6 | Parrot | Bird     |      2 |
+----+--------+----------+--------+

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

一个非常好的解决方案是使用用户定义的变量,例如

select
id,
name,
category,
rn as `count`
from (
  select
  id,name,category,
  @rn:= if(category = @prev_category,@rn+1,1) as rn,
  @prev_category:= category
  from my_table,(select @rn:=1,@prev_category:= null)x
  order by category,id
)x

答案 1 :(得分:0)

基本上你需要等同于ROW_NUMBER OVER(PARTITION),你可以使用自联接和聚合:

SELECT a.id, a.name, a.category, count(*) AS `Count`
FROM tab a
JOIN tab b 
  ON a.Category= b.Category AND a.ID >= b.ID
GROUP BY a.id, a.name, a.category;

LiveDemo

输出:

╔════╦════════╦══════════╦═══════╗
║ ID ║  Name  ║ Category ║ Count ║
╠════╬════════╬══════════╬═══════╣
║  1 ║ Cat    ║ Animal   ║     1 ║
║  2 ║ Loin   ║ Animal   ║     2 ║
║  3 ║ Dog    ║ Animal   ║     3 ║
║  4 ║ Red    ║ Color    ║     1 ║
║  5 ║ Hen    ║ Bird     ║     1 ║
║  6 ║ Parrot ║ Bird     ║     2 ║
╚════╩════════╩══════════╩═══════╝