MYSQL:根据唯一的行值向表中添加唯一的数值?
我有这个表,我想把它分成三个表,这样我就有了名称,名称和顺序之间的关系表,第三个表只包含顺序。所以我认为一个简单的方法是在这里添加一个唯一的数字列MYSQL:根据唯一的行值向表中添加唯一的数值?,mysql,Mysql,我有这个表,我想把它分成三个表,这样我就有了名称,名称和顺序之间的关系表,第三个表只包含顺序。所以我认为一个简单的方法是在这里添加一个唯一的数字列 +----+------+-----------------------+-------+--------------+ | id | name | address | phone | order_number | +----+------+-----------------------+-------+---------
+----+------+-----------------------+-------+--------------+
| 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 |
+----+------+-----------------------+-------+--------------+
我想添加一个数字列,该列具有与唯一名称值相关联的递增数字,以便得到预期的结果
+----+------+-----------------------+-------+--------------+---+
| 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 |
+----+------+-----------------------+-------+--------------+---+
我该怎么做呢?通过使用用户定义的变量,得到一些类似于您期望的结果集的结果
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
注:以上说明不能保证顺序,它将完全取决于id列值
如果您只想显示NID,那么@M Khalid Junaid的答案就可以了 但如果要在表中添加列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列
希望有帮助 您只是想将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
);