반응형
단일 쿼리로 mysql 테이블에서 모든 부모 찾기(Recursive Query)
이 스키마가 있습니다.
샘플 데이터
| ID | TITLE | CONTROLLER | METHOD | PARENT_ID |
|----|-------------------|------------|-------------------|-----------|
| 1 | Dashboard | admin | dashboard | 0 |
| 2 | Content | admin | content | 0 |
| 3 | Modules | admin | modules | 0 |
| 4 | Users | admin | users | 0 |
| 5 | Settings | admin | settings | 0 |
| 6 | Reports | admin | reports | 0 |
| 7 | Help | admin | help | 0 |
| 8 | Pages | content | pages | 2 |
| 9 | Media | content | media | 2 |
| 10 | Articles | content | articles | 2 |
| 11 | Menues | content | menues | 2 |
| 12 | Templates | content | templates | 2 |
| 13 | Themes | content | themes | 2 |
| 14 | Blog | content | blog | 2 |
| 15 | Forum | content | forum | 2 |
| 16 | Core Modules | modules | core_module | 3 |
| 17 | User Modules | modules | user_module | 3 |
| 18 | All Users | users | all_users | 4 |
| 19 | Groups | users | groups | 4 |
| 20 | Permissions | users | permissions | 4 |
| 21 | Import and Export | users | import_export | 4 |
| 22 | Send Email | users | send_mail | 4 |
| 23 | Login Records | users | login_records | 4 |
| 24 | General Settings | settings | general_settings | 5 |
| 25 | Email Settings | settings | email_settings | 5 |
| 26 | Popular Content | reports | popular_content | 6 |
| 27 | Most Active Users | reports | most_active_users | 6 |
| 28 | Documentation | help | documentation | 7 |
| 29 | About | help | about | 7 |
| 30 | Products | products | product | 17 |
| 31 | Categories | categories | category | 17 |
SQL Fiddle 데모.샘플 데이터를 몇 개 삽입했습니다.
챌린지
제목이 어디에 있는지 기록의 부모들을 모두 찾아야 합니다.Categories
. 어떻게 하면 한 번의 질의만으로 모든 부모들을 얻을 수 있을까요?
제 말은 이 결과가 필요하다는 것입니다.
원하는 출력
id | title | controller | method | url | parent_id
----------------------------------------------------------------
3 | Modules | admin | modules | (NULL) | 0
17 | User Modules | modules | user_module | (NULL) | 3
31 | Categories | categories | category | (NULL) | 17
모든 상위 항목이 있는 항목을 가져오고 where 조건을 사용한다고 가정합니다.id = 31
, 기록을 넘어서야 합니다
SELECT T2.id, T2.title,T2.controller,T2.method,T2.url
FROM (
SELECT
@r AS _id,
(SELECT @r := parent_id FROM menu WHERE id = _id) AS parent_id,
@l := @l + 1 AS lvl
FROM
(SELECT @r := 31, @l := 0) vars,
menu m
WHERE @r <> 0) T1
JOIN menu T2
ON T1._id = T2.id
ORDER BY T1.lvl DESC;
언급URL : https://stackoverflow.com/questions/12948009/finding-all-parents-in-mysql-table-with-single-query-recursive-query
반응형
'programing' 카테고리의 다른 글
RestTemplate 스레드는 안전합니까? (0) | 2023.10.24 |
---|---|
StackOverflow와 같은 "토스트" 메시지 생성 (0) | 2023.10.24 |
DBMS Profiler를 사용한 PL/SQL 커버리지 보고서 구축 (0) | 2023.10.24 |
SBT 스칼라 프로젝트에서 MySQL JDBC 드라이버를 사용하는 방법? (0) | 2023.10.24 |
엄격한 별칭 규칙이 잘못 지정되었습니까? (0) | 2023.10.24 |