하나의 행만 선택하는 동안 총 행 번호 가져오기
관련/비슷한 질문:MySQL - 행 번호 가져오기 선택, 부분 결과만 선택, 총 행 수 가져오기
현재 다음 테이블이 있습니다.
+----+--------------------+---------------+--------+
| id | accountId | competitionId | rating |
+----+--------------------+---------------+--------+
| 1 | theidoftheaccount1 | 1 | 100 |
| 2 | theidoftheaccount2 | 3 | 90 |
| 3 | theidoftheaccount3 | 1 | 80 |
| 4 | theidoftheaccount4 | 1 | 50 |
+----+--------------------+---------------+--------+
와 싸우고 싶다.accountId='theidoftheaccount3'
일반적인 SQL 문을 호출합니다.SELECT * FROM competitors WHERE competitionId='someotherid1' AND accountId='theidoftheaccount3 ' ORDER BY rating DESC
모든 게 다 좋아
문제:여기서 얻은 행의 행 번호를 알고 싶은데, 이 행의 행 번호는,competitionId='someotherid1'
이 행 번호는 같은 경기에서 다른 모든 선수 중 선수의 '랭크'가 된다.
그래서 기본적으로 하루의 끝에 다시 돌아오곤 했다.
+----+--------------------+---------------+--------+-----------+
| id | accountId | competitionId | rating | rowNumber |
+----+--------------------+---------------+--------+-----------+
| 3 | theidoftheaccount3 | 1 | 80 | 2 |
+----+--------------------+---------------+--------+-----------+
이것이 어떻게 행해지는가?
한 가지 방법은row_number()
서브쿼리:
select c.*
from (select c.*,
rank() over (partition by competitionid order by rating desc) as ranking
from competitors c
where competitionId = 'someotherid1'
) c
where accountId = 'theidoftheaccount3';
편집:
창 기능이 없는 다른 방법은 다음과 같습니다.
select count(*) + 1 as ranking
from competitors c
where c.competitionId = 'someotherid1' and
c.rating > (select c2.rating
from competitors c2
where c2.competitionid = c.competitionId and
c2.accountId = 'theidoftheaccount3'
);
데이터베이스가 창 기능을 지원하지 않는 경우 하위 쿼리를 사용할 수도 있습니다.
select
t.*,
(
select count(*) + 1
from mytable t1
where t1.competitionId = t.competitionId and t1.rating > t.rating
) row_num
from mytable t
where t.accountId = 'theidoftheaccount3'
성능을 위해 열에 대한 인덱스를 원합니다.(competitionId, rating)
(다른 하나는 컬럼에 있습니다).accountId
하지만, 이것은 아마도 이미 존재하는 것 같습니다.unique
열)을 클릭합니다.
언급URL : https://stackoverflow.com/questions/59603207/get-total-row-number-while-only-selecting-a-single-row
'source' 카테고리의 다른 글
printf()에서 0 뒤에 오는 것을 피합니다. (0) | 2022.11.15 |
---|---|
VueJ에서 선택한 인덱스를 감지하는 방법 (0) | 2022.11.15 |
MySQL의 ROW_NUMBER() (0) | 2022.11.15 |
php mysqli_connect: 클라이언트에 알 수 없는 인증방식 [http_sha2_password] (0) | 2022.11.15 |
'==' 또는 'is'를 사용하여 문자열을 비교하면 결과가 달라질 수 있는 이유는 무엇입니까? (0) | 2022.11.15 |