2017-10-14 53 views
0

我有这张表,我想把它分成三张表,所以我有名称,名称和订单之间的关系表,以及第三个只包含订单。所以,我认为一个简单的方法可能是在这里补充一个唯一的编号列MYSQL:基于唯一的行值为表添加唯一的数值?

+----+------+-----------------------+-------+--------------+ 
| id | name | address    | phone | order_number | 
+----+------+-----------------------+-------+--------------+ 
| 1 | Joe | Joes Address   | 1111 | 1390842  | 
| 2 | Paul | Pauls Address   | 2222 | 9082309  | 
| 3 | Greg | Gregs Address   | 3333 | 0928340  | 
| 4 | Lucy | Lucys Address   | 4444 | 9028340  | 
| 5 | Paul | Pauls Address   | 2222 | 8958399  | 
| 6 | Tom | Toms Address   | 5555 | 9084024  | 
| 7 | Lucy | Lucys Another Address | 4444 | 9801983  | 
| 8 | Paul | Pauls Another Address | 2222 | 0982304  | 
+----+------+-----------------------+-------+--------------+ 

,我想用独特的name值相关联的递增的数字添加数字列,使该预期的结果

+----+------+-----------------------+-------+--------------+---+ 
| id | name | address    | phone | order_number |NID| 
+----+------+-----------------------+-------+--------------+---| 
| 1 | Joe | Joes Address   | 1111 | 1390842  | 1 | 
| 2 | Paul | Pauls Address   | 2222 | 9082309  | 2 | 
| 3 | Greg | Gregs Address   | 3333 | 0928340  | 3 | 
| 4 | Lucy | Lucys Address   | 4444 | 9028340  | 4 | 
| 5 | Paul | Pauls Address   | 2222 | 8958399  | 2 | 
| 6 | Tom | Toms Address   | 5555 | 9084024  | 5 | 
| 7 | Lucy | Lucys Another Address | 4444 | 9801983  | 4 | 
| 8 | Paul | Pauls Another Address | 2222 | 0982304  | 2 | 
+----+------+-----------------------+-------+--------------+---+ 

我该怎么做?

+0

你只是想显示NID作为查询结果或想要添加表中的列吗? –

回答

1

有些什么类似通过使用用户定义的变量

select `id`, `name`, `address`, `phone`, `order_number`, 
@b:= case when `name` <> @a then @b + 1 else @b end NID, 
@a:= `name` 
from (
    select * 
    from demo b, 
    (select @a:=null,@b:=1) a 
    order by name 
) c 

DEMO

另一种简单的版本,通过假设id列设置你想要的结果设置为自动递增,如果这样,那么你可以使用相关子查询挑最小的ID为同名记录

select a.*, 
(select min(id) from demo b where a.name = b.name) nid 
from demo a 

注一波夫将不能保证它会完全依赖于id列值

DEMO

0

如果你只是想显示的NID序列,然后@M哈立德朱奈德的回答将正常工作。

但是如果你想添加的列NID在表中,那么下面的查询将完成这项工作:

alter table t 
add column nid integer; 

update t 
set nid = (Select 
      (case when count(name)>1 then min(id) 
       else id 
      end) 
      from 
      (select *from t) x 
      where t.name = x.name   
      ); 

注:Nid不含有增量序列。它基于id列。

希望它有帮助!

+0

它按预期工作吗? –