programing

ASC로 주문(하단에 널 포함)

javamemo 2023. 10. 27. 21:39
반응형

ASC로 주문(하단에 널 포함)

저는 학교 테이블과 지역 테이블을 연결하는 SQL 쿼리를 작성하고 있습니다.각 학교가 하나의 지역에 붙어있는 단순한 일대다 관계.제 질문은 다음과 같습니다.

SELECT 
    schools.id AS schoolid,
    schools.name AS school, 
    districts.id AS districtid, 
    districts.name AS district
FROM sms_schools AS schools
    LEFT JOIN sms_districts AS districts ON schools.districtid = districts.id
WHERE 1 = 1
ORDER BY districts.name, schools.name

제가 레프트조인을 한 이유는 모든 학교가 지역구에 붙어있지 않기 때문입니다.예를 들어, 한 학교는 홈스쿨링을 받는 모든 학생들을 포함할 수 있습니다.그건 지역에 없을 겁니다.

그래서 제가 하고 싶은 일은 ORDER BY를 지역명과 학교명 그대로 주문하는 것입니다.유일한 문제는 출력이 끝날 때 '기타'라는 그룹을 사용할 수 있도록 null district가 하단에 있기를 원한다는 것입니다.

출력 끝에 null로 오름차순으로 주문 가능한가요?

질문을 한 지 1분 만에 답을 찾았습니다.절별 순서에서 null을 다른 것보다 높은 값으로 만들기 위해 case를 사용합니다.

 ORDER BY (CASE WHEN districts.id IS NULL then 1 ELSE 0 END),districts.name, schools.name;

당신은 사용할 수 있습니다.ISNULL()기능.

MySQL 설명서에서 다음을(를)

ISNULL()expr)

한다면exprNULL,ISNULL()돌아온다1, 그렇지 않으면 되돌아옵니다.0.

를 들어,

ORDER BY ISNULL(districts.name), districts.name, schools.name

나는 이것 대신에 이것을 사용하는 것을 좋아합니다.CASEMySQL에 대한 옵션.휴대용이 아니라는 것만 알아둬요.ISNULL()는 표준 SQL이 아니며 다른 버전의 SQL에서는 다르게 작동합니다.

기본적으로 Null은 맨 위에 표시되지만 IsNull을 사용하여 기본값을 할당할 수 있으므로 필요한 위치에 Null을 배치할 수 있습니다.


SELECT schools.id AS schoolid,schools.name AS school, districts.id AS districtid, districts.name AS district FROM sms_schools AS schools LEFT JOIN sms_districts AS districts ON schools.districtid = districts.id WHERE 1 = 1 
ORDER BY isnull(districts.name,'1'), schools.name 

SELECT
 schools.id AS schoolid,
 schools.name AS school,
 districts.id AS districtid,
 districts.name AS district,
 if(schools.districtid IS NULL,1,0) as sort 
FROM sms_schools AS schools
LEFT JOIN sms_districts AS districts 
 ON schools.districtid = districts.id
WHERE 1 = 1
ORDER BY sort, districts.name, schools.name

'new' 컬럼에 정렬 규칙을 추가하고 코드에서 필드를 숨긴 숫자를 사용하여 if를 직접 정렬할 수 있는지 테스트합니다(if...로 정렬).

행운을 빌어요

언급URL : https://stackoverflow.com/questions/5993109/order-by-asc-with-nulls-at-the-bottom

반응형