合并为单个查询

时间:2017-03-24 10:00:42

标签: mysql sql

使用最短和最长的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 个答案:

答案 0 :(得分: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