2014-09-28 55 views
0

首先,感謝大家花時間幫助解決我的問題。MYSQL - 查找不同的記錄並按其他字段排序

我有包括idcontent

一個例子組數據表:

id content 
9 With astonishing insight and poignant precision 
8 Whether they find themselves hacking rattles from the tails of snakes or nesting rattles in the hands of their babies. 
4 This is a clear-eyed, deeply poignant collection. 
12 This book is a dynamic compilation of snapshot tales, each of which encompasses its own sensory-rich world and can be read. 
12 This book is an appropriate title for her collection-the prose poems feel revealed. 
12 This book is a collection of ekphrastic vignettes set against surreal backdrops fraught with eerie characters faking normalcy. 

我需要做的就是找到最短長度content爲每一個獨特id

例如,上面的輸出應該是:

id content 
9 With astonishing insight and poignant precision 
8 Whether they find themselves hacking rattles from the tails of snakes or nesting rattles in the hands of their babies. 
4 This is a clear-eyed, deeply poignant collection. 
12 This book is an appropriate title for her collection-the prose poems feel revealed. 

我有什麼,到目前爲止,顯然是錯誤的是:

SELECT DISTINCT id, content FROM t 
    GROUP BY id; 

謝謝您的幫助!

回答

0

一種方法是計算最短長度,然後加入結果回:

select t.id, t.content 
from (select id, min(length(content)) as minl 
     from t 
     group by id 
    ) tmin join 
    t 
    on t.id = tmin.id and length(t.content) = tmin.minl; 

注意:如果兩個內容具有相同的長度,並且是最小的,這將返回他們兩個。你的問題沒有具體說明在這種情況下要做什麼。

+0

戈登,謝謝!如果他們長度相同,我不會過分擔心。我更感興趣的是確保我提供的內容不是我的意圖太長,而不是特定的內容元素本身。 – amac 2014-09-28 15:24:18

+0

@amac。 。 。你可以選擇一個任意的「內容」,並使用「left()」來獲得第一個「n」個字符。 – 2014-09-28 15:39:27

+0

這是一個很好的建議,但是,我需要顯示'content'字段的完整值,而不是截斷的字段值。 – amac 2014-09-28 15:48:43

相關問題