我有一个MySQL表,它有两列id
和uuid
++++++++++++++
+ ID | UUID +
++++++++++++++
+ 74 | 3210 +
+ 75 | 3210 +
+ 76 | 3210 +
+ 77 | 3310 +
+ 78 | 3310 +
+ 79 | 3410 +
++++++++++++++
我需要使用mysql查询输出如下
+++++++++++++++
+ ID | UUID +
+++++++++++++++
+ 74 | 3210 +
+ 75 | 3210-1 +
+ 76 | 3210-2 +
+ 77 | 3310 +
+ 78 | 3310-2 +
+ 79 | 3410 +
++++++++++++++
答案 0 :(得分:1)
试试这个:
SELECT ID,
CONCAT(CAST(UUID AS CHAR(4)),
IF(rn = 0, '', CONCAT('-', CAST(rn AS CHAR(4))))) AS UUID
FROM (
SELECT ID, UUID,
@rn := IF(@id = UUID, @rn + 1,
IF(@id := UUID, 0, 0)) AS rn
FROM mytable
CROSS JOIN (SELECT @rn := 0, @id := 0) AS rn
ORDER BY UUID, ID) AS t
答案 1 :(得分:1)
您也可以通过提供行号来完成。
<强>查询强>
select t1.ID,
(case when t1.rn > 1
then concat(cast(t1.UUID as char(4)), '-', (t1.rn - 1))
else t1.UUID end) as UUID
from
(
select ID, UUID,
(
case UUID when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := UUID end
) as rn
from my_table t,
(select @curRow := 0, @curA := '') r
order by ID
)t1;
<强>结果强>
+----+--------+
| ID | UUID |
+----+--------+
| 74 | 3210 |
| 75 | 3210-1 |
| 76 | 3210-2 |
| 77 | 3310 |
| 78 | 3310-1 |
| 79 | 3410 |
+----+--------+
答案 2 :(得分:0)
SELECT t1.ID, if(t1.rank=0, t1.uuid,concat(t1.uuid,"-",rank))
FROM
(
SELECT ID, uuid,@rank := if(@uuid = uuid, @rank ,-1) + 1 rank, @uuid := uuid
FROM my_table,(SELECT @uuid :='', @rank :=0) vars
ORDER BY uuid
) t1