2017-03-24 82 views
0

用最短和最長的CITY名稱及其各自的長度(即名稱中的字符數)查詢STATION中的兩個城市。如果有多個最小或最大的城市,請選擇按字母順序排列的第一個城市。合併爲單個查詢

SELECT CITY,CHAR_LENGTH(CITY) AS CHARLENGTH 
FROM STATION 
ORDER BY CHARLENGTH ASC 
LIMIT 1; 

SELECT CITY,CHAR_LENGTH(CITY) AS CHARLENGTH 
FROM STATION 
ORDER BY CHARLENGTH DESC 
LIMIT 1; 

回答

1

是這樣的嗎?

##DROP TABLE STATION; 
CREATE TABLE STATION (CITY VARCHAR(100)); 
INSERT INTO STATION VALUES ('aaaaaaa'); 
INSERT INTO STATION VALUES ('bbbbbbb'); 
INSERT INTO STATION VALUES ('cccc'); 
INSERT INTO STATION VALUES ('dd'); 
SELECT * 
FROM 
(SELECT CITY,CHAR_LENGTH(CITY) AS CHARLENGTH FROM STATION ORDER BY CHARLENGTH ASC, CITY LIMIT 1) A 
UNION ALL 
SELECT * FROM 
(SELECT CITY,CHAR_LENGTH(CITY) AS CHARLENGTH FROM STATION ORDER BY CHARLENGTH DESC, CITY LIMIT 1) B 

輸出:

CITY CHARLENGTH 
1 dd 2 
2 aaaaaaa 7