2010-04-06 24 views

risposta

1

mi chiedo se questo dovrebbe funzionare:

select * from table where id in (select distinct max(id) from table group by name) 
+0

È possibile ottenere troppe righe. La tua dichiarazione restituisce tutte le righe con un ID che è il massimo di qualsiasi gruppo (non necessariamente il gruppo a cui appartiene questa riga). Considera le seguenti coppie (id, name): (1, foo), (2, foo), (2, bar), (3, bar). Si desidera recuperare (2, pippo) e (3, barra), ma la query restituisce anche (2, bar) poiché 2 è il massimo del gruppo foo. – titanoboa

+0

Aggiunto DISTINCT per selezionare – Riho

0
SELECT di.id, di.orderer, di.ghigh, di.glow 
FROM (
     SELECT glow, MIN(orderer) AS orderer 
     FROM t_distinct d 
     GROUP BY 
       glow 
     ) dd 
JOIN t_distinct di 
ON  di.id = 
     (
     SELECT id 
     FROM t_distinct ds 
     WHERE ds.glow = dd.glow 
       AND ds.orderer = dd.orderer 
     ORDER BY 
       glow DESC, orderer DESC, id DESC 
     LIMIT 1 
     ) 

Vedere questo articolo per ulteriori spiegazioni:

0

Guardate la seguente query:

SELECT items.* 
FROM items, (select @grouping_value:=null) as init 
WHERE GREATEST([email protected]_value, 
       IF(@grouping_value:=grouping_field,0,0)) 
ORDER BY grouping_field, sorted_field DESC 

L'idea è di ordinare i dati della tabella raggruppando campo e campo ordinato e prendere la prima riga di ciascun gruppo

1

I imbattuti questa discussione quando si lavora su un codice foro. Volevo ottenere l'ultimo post per ogni thread e visualizzarlo nell'elenco di thread per una scheda particolare.

La risposta di Quassnoi sopra è stata molto utile per me e ho potuto adattarla. Ecco il codice nel caso in cui aiuti qualcun altro:

SELECT p.id As post_id, p.post_number, p.topic_id 
FROM forum_post p, (
    SELECT topic_id, MAX(post_number) As max_post_number 
    FROM forum_post d 
    GROUP BY topic_id) dd 
WHERE p.id = 
(
    SELECT id 
    FROM forum_post 
    WHERE topic_id = dd.topic_id 
    AND post_number = dd.max_post_number 
    ORDER BY topic_id DESC, post_number DESC, id DESC 
    LIMIT 1 
) 
Problemi correlati