說,我有這張桌子。如何在MySQL中爲此問題編寫查詢?
name category position
apple fruit 5
apple red 3
melon big null
如果一個名稱屬於多於一個類別,我想要一個與最低的位置。
結果:
name category position
apple red 3
melon big null
如何做到這一點?
說,我有這張桌子。如何在MySQL中爲此問題編寫查詢?
name category position
apple fruit 5
apple red 3
melon big null
如果一個名稱屬於多於一個類別,我想要一個與最低的位置。
結果:
name category position
apple red 3
melon big null
如何做到這一點?
null
使這個棘手。我不確定它應該被認爲是「高」還是「低」。讓我來承擔 「低」:
select t.*
from t
where coalesce(t.position, -1) = (select min(coalesce(t2.position, -1))
from t t2
where t2.name = t.name
);
具有相同位置的多行如何? –
@UsagiMiyamoto。 。 。這是OP的恰當問題。問題的措辭表明「最低」的立場是獨一無二的。 –
你試過這個查詢嗎?因爲結果是錯誤的。 – CrazySabbath
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]
這一個給出了正確的結果:http://sqlfiddle.com/#!9/f68cad/5 – CrazySabbath
又是什麼一個'null'位置是什麼意思? –