簡體   English   中英

有人可以說我在 mysql 中做錯了什么嗎?

[英]Can someone say what i do wrong in mysql?

Hackerrank下面的任務中,我做了那個查詢

SELECT CITY ,length(CITY ) from STATION where length(CITY )in(
select max(length(CITY ))from STATION union select min(length(CITY ))from STATION )Group by length(CITY )
 order by length(CITY ) desc,CITY ;

我收到了錯誤,我也做了另一個這樣的查詢

Select max(length(CITY)),CITY from STATION Group by length(CITY) Order by length(CITY)Desc;

並收到該錯誤Error

疑問句如下:

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

您實際上並不需要聚合來完成此任務。

我認為用union all和兩個行限制查詢(一個按升序長度對城市進行排序,另一個按降序長度對城市進行排序)來表達會更簡單:

(
    select city, char_length(city) cnt_chars 
    from station 
    order by char_length(city), city limit 1
) union all (
    select city, char_length(city) 
    from station 
    order by char_length(city) desc, city limit 1
)

如果表中只有一個城市(或者如果所有城市的長度相同),則union可能比union all更合適(因此同一個城市不會在結果集中出現兩次)。

或者,如果您運行的是 MySQL 8.0,則可以使用窗口函數:

select city, cnt_chars 
from (
    select s.*,
        row_number() over(order by char_length(city), city) rn_asc,
        row_number() over(order by char_length(city) desc, city) rn_desc
    from station s
) s
where 1 in (rn_asc, rn_desc)

旁注: char_length()length()更安全。 前者計算字符數,而后者計算字節數(如果您的字符串有多字節字符,這不是您想要的)。

您正在嘗試選擇CITY名稱和length(CITY)但僅按length(CITY)分組。 如果兩個或多個城市的length(CITY)有某個值,mysql 不知道應該選擇哪個CITY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM