반응형
시간별로 정렬하고 특정 ID 뒤에 n개의 행을 반환하는 MySQL 쿼리
데이터베이스에 다음과 같은 테이블(버전: MariaDB 10.3.17, MySQL 5.7)이 있습니다.
id name timestamp
-----------------------------
154875 AXC 154875869
362574 RTB 154875800
962548 MNV 154875969
365847 XRT 154875123
...
필요한 것:
- 타임스탬프의 행을 내림차순으로 정렬하다
- 그런 다음 (필수) 뒤에 24 행을 반환합니다. 여기서 id=something
예를 들어 id=962548의 경우 예상 출력의 처음 3행은 다음과 같습니다.
id name timestamp
-----------------------------
154875 AXC 154875869
362574 RTB 154875800
365847 XRT 154875123
MySQL에서 구현하려면 어떻게 해야 합니까?
ID = something인 행을 사용자의 조건에서 테이블로 반환하는 쿼리에 참여하십시오.
select t.*
from tablename t
inner join (select * from tablename where id = 365847) c
on t.timestamp < c.timestamp or (t.timestamp = c.timestamp and t.id < c.id)
order by t.timestamp desc, t.id desc
limit 24
하지만 아래가 무슨 뜻인지 잘 모르기 때문에 반대 순서를 원할 수도 있습니다.
select t.*
from tablename t
inner join (select * from tablename where id = 365847) c
on t.timestamp > c.timestamp or (t.timestamp = c.timestamp and t.id > c.id)
order by t.timestamp desc, t.id desc
limit 24
다음과 같은 쿼리를 사용하여 타임스탬프 값이 id 타임스탬프보다 큰 요소를 선택해야 합니다.
SELECT *
FROM table
WHERE timestamp>(select timestamp
from table
where id = 'current_id')
ORDER BY timestamp LIMIT 24;
나는 다음과 같이 질문할 것이다.
SELECT * FROM tab
WHERE timestamp >= (SELECT timestamp FROM tab WHERE id = 154875)
AND id <> 154875
ORDER BY timestamp DESC, id DESC
LIMIT 2
언급URL : https://stackoverflow.com/questions/63263112/mysql-query-to-order-by-time-and-return-n-rows-after-specific-id
반응형
'sourcecode' 카테고리의 다른 글
MariaDB 10.3.9에서 PHP-7.1.20을 컴파일하는 동안 오류가 발생했습니다. (0) | 2022.09.19 |
---|---|
PHP 파일 크기 MB/KB 변환 (0) | 2022.09.19 |
PHP 계산 기간 (0) | 2022.09.19 |
errno: 150 "외부 키 제약 조건이 잘못 형성되었습니다") MariaDB (0) | 2022.09.19 |
MySQL 최대 메모리 사용량 (0) | 2022.09.19 |