이베리스
Iberis
이베리스
전체 방문자
오늘
어제
  • 전체보기 (72)
    • Course (64)
      • MS-SQL (10)
      • MY-SQL (12)
      • Oracle (2)
      • PostgreSQL (1)
      • ASP.NET with C# (5)
      • PHP (14)
      • Java (1)
      • javaScript (11)
      • A quick tip (1)
      • CodeIgniter (1)
      • CSS (3)
      • 운영체제 (2)
      • Git (1)
      • 리눅스 (0)
    • Utility (4)
    • 와우 (2)
      • 애드온 (2)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 렌카드
  • 이베리스
  • 콤마
  • 와우클래식
  • 테이블
  • Benik
  • 15517
  • comma
  • table
  • 자동 줄 바꿈
  • wowclassic
  • 수동삭제
  • 보안 주체
  • 3DP
  • 3자리
  • Elv
  • 쿼리
  • 테이블 복사
  • 접속안됨
  • 삭제
  • 공유폴더
  • dbo
  • MSSQL
  • width
  • 19c
  • 구조 복사
  • error
  • 1326
  • share
  • power point

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
이베리스

Iberis

Course/MY-SQL

MySQL row_number 구현

2015. 4. 28. 10:28

Add row number for each row

To emulate the  row_number function in MySQL, you have to use session variables in the query. The following example selects 5 employees from the  employees table and adds row number for each row, starting from 1.

1
2
3
4
5
6
7
SET @row_number = 0;
 
SELECT
    (@row_number:=@row_number + 1) AS num, firstName, lastName
FROM
    employees
LIMIT 5;

MySQL row_number Function

In the query above:

  • First, we defined a variable named  row_number and set its value to 0.
  • Then, in the query, we increased the value of the  row_number variable to 1 for each row.

Another technique is to use a session variable as a derived table and crossed join it with the main table. See the following query:

1
2
3
4
5
SELECT
    (@row_number:=@row_number + 1) AS num, firstName, lastName
FROM
    employees,(SELECT @row_number:=0) AS t
LIMIT 5;

Notice that the derived table must have its own alias to make the query syntactically correct.

Add row number for each group

How about  row_number “over partition by” functionality? For example, what if we want to add row number to each group, and it is reset for every new group. Let’s take a look at the payments table:

1
2
3
4
5
SELECT
    customerNumber, paymentDate, amount
FROM
    payments
ORDER BY customerNumber;

payments table

Suppose for each customer, we add a row number, and the row number is reset for the new customer. To achieve this, we have to use two session variables, one for the row number and the other for storing the old customer number to compare it with the current one as the following query:

1
2
3
4
5
6
7
8
9
10
11
SELECT
    @row_number:=CASE
        WHEN @customer_no = customerNumber THEN @row_number + 1
        ELSE 1
    END AS num,
    @customer_no:=customerNumber as CustomerNumber,
    paymentDate,
    amount
FROM
    payments
ORDER BY customerNumber;

We used CASE statement in the query. If the customer number remains the same, we increase the  row_number variable, otherwise we reset it to 1. The result of the query is as screenshot below.

Like the  row_number for each row, we can use derived table and cross join technique to produce the same result.

1
2
3
4
5
6
7
8
9
10
11
SELECT
    @row_number:=CASE
        WHEN @customer_no = customerNumber THEN @row_number + 1
        ELSE 1
    END AS num,
    @customer_no:=customerNumber as CustomerNumber,
    paymentDate,
    amount
FROM
    payments,(SELECT @customer_no:=0,@row_number:=0) as t
ORDER BY customerNumber;

In this tutorial, we have shown you how to emulate the row_number function in MySQL.


출처: http://www.mysqltutorial.org/mysql-row_number/

저작자표시 비영리 변경금지 (새창열림)

'Course > MY-SQL' 카테고리의 다른 글

MySql 계층적 조회 쿼리  (0) 2015.05.12
MSSQL에서 MySQL 스토어드 프로시저(Stored PROCEDURE) 변경방법  (0) 2015.04.30
[mysql] 쿼리값이 NULL 일때 0으로 바꾸기  (0) 2014.09.01
[MYSQL] 조인, JOIN (INNER JOIN, OUTER JOIN)  (0) 2014.09.01
문자열or텍스트 와 필드 값을 합치는 방법  (0) 2014.04.25
    'Course/MY-SQL' 카테고리의 다른 글
    • MySql 계층적 조회 쿼리
    • MSSQL에서 MySQL 스토어드 프로시저(Stored PROCEDURE) 변경방법
    • [mysql] 쿼리값이 NULL 일때 0으로 바꾸기
    • [MYSQL] 조인, JOIN (INNER JOIN, OUTER JOIN)
    이베리스
    이베리스
    Developer

    티스토리툴바