2017-10-14 1 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  | 
+----+------+-----------------------+-------+--------------+ 

여기에 고유 번호의 열을 추가 할 수 있다고 생각하고 예상 된 결과가

+----+------+-----------------------+-------+--------------+---+ 
| 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 | 
+----+------+-----------------------+-------+--------------+---+ 
수 있도록 나는 독특한 name 값과 관련된 증분 번호로 숫자 열을 추가 할

어떻게하면됩니까 ??

+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 

참고 a를 기록 보브 방금 전국 면역의 날을 표시하려는 경우 완전히 ID 열 값

DEMO

0

에 따라 달라집니다 순서를 보장하지 않습니다, 다음 @M 칼리드 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 열을 기반으로합니다.

희망이 있습니다.

+0

예상대로 작동합니까? –

관련 문제