2014-03-06 74 views
0

我的SQL查詢樣子:組由數以最小長度

select CategoryID, Name, count(Name) as C 
from Posts 
where CategoryID=1101 and Language=1 
group by CategoryID 
order by C ASC; 

我需要在最短的名稱在由名稱分組的類別,任何想法?

如果沒有給出CategoryID(NULL)該組將不包含,那麼另一件事將會很棒。

回答

1

這將這樣的伎倆:

SELECT 
    CategoryID, 
    SUBSTRING_INDEX(GROUP_CONCAT(Name ORDER BY LENGTH(Name)), ',', 1) As s_name, 
    Count(Name) as C, 
FROM 
    Posts 
WHERE 
    CategoryID=1101 and Language=1 
GROUP BY CategoryID 
ORDER BY C ASC; 
0

你可以做到這一點通過length(Name)下令,限制爲1

select CategoryID, Name, count(Name) as C 
from Posts where CategoryID is not null and Language=1 
group by CategoryID order by length(Name) asc limit 1; 

添加CategoryID IS NOT NULL排除NULL值。