2017-07-31 54 views
-2

說,我有這張桌子。如何在MySQL中爲此問題編寫查詢?

name  category position 
apple  fruit  5 
apple  red   3 
melon  big  null 

如果一個名稱屬於多於一個類別,我想要一個與最低的位置。

結果:

name  category position 
apple  red   3 
melon  big  null 

如何做到這一點?

+3

又是什麼一個'null'位置是什麼意思? –

回答

2

null使這個棘手。我不確定它應該被認爲是「高」還是「低」。讓我來承擔 「低」:

select t.* 
from t 
where coalesce(t.position, -1) = (select min(coalesce(t2.position, -1)) 
            from t t2 
            where t2.name = t.name 
           ); 
+0

具有相同位置的多行如何? –

+0

@UsagiMiyamoto。 。 。這是OP的恰當問題。問題的措辭表明「最低」的立場是獨一無二的。 –

+0

你試過這個查詢嗎?因爲結果是錯誤的。 – CrazySabbath

1
SELECT 
    f.* 
FROM 
(
    SELECT 
     name, 
     MIN(IFNULL(position,0)) as min_position 
    FROM 
     fruits 
    GROUP BY 
     name 
) tmp 
LEFT JOIN 
    fruits f ON 
    f.name = tmp.name AND 
    IFNULL(f.position,0) = min_position 
-- GROUP BY name 
-- optional if multiple (name, position) are possible for example 
-- [apple,fruit,5], [apple,red,5] 
+0

這一個給出了正確的結果:http://sqlfiddle.com/#!9/f68cad/5 – CrazySabbath