2011-10-20 12 views
13

Questa è la struttura della tabellaCome selezionare per MAX (data)?

CREATE TABLE `reports` (
    `report_id` int(11) NOT NULL auto_increment, 
    `computer_id` int(11) NOT NULL default '0', 
    `date_entered` datetime NOT NULL default '1970-01-01 00:00:00', 
    `total_seconds` int(11) NOT NULL default '0', 
    `iphone_id` int(11) default '0', 
    PRIMARY KEY (`report_id`), 
    KEY `computer_id` (`computer_id`), 
    KEY `iphone_id` (`iphone_id`) 
) ENGINE=MyISAM AUTO_INCREMENT=120990 DEFAULT CHARSET=latin1 

ho bisogno di una dichiarazione SELECT che elencherà il report_id per computer_id da ultimo entrato date_entered, e non ho idea di come farlo. Qualcuno può indicarmi la giusta direzione? Grazie in anticipo.

risposta

28

Questo dovrebbe farlo:

SELECT report_id, computer_id, date_entered 
FROM reports AS a 
WHERE date_entered = (
    SELECT MAX(date_entered) 
    FROM reports AS b 
    WHERE a.report_id = b.report_id 
     AND a.computer_id = b.computer_id 
) 
+2

Quasi. Ho omesso "a.report_id = b.report_id" e questo ha funzionato. Grazie – poetter747

+2

Questo è un po 'inefficiente perché stai generando troppe sottoquery. Invece, prova ad usare una sottoquery non correlata. https://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html – Pablo

+0

Pablo è corretto. Il filtraggio può essere fatto prima unendo una subquery, risparmiando così le prestazioni. – twicejr

11

Si desidera solo che mostri l'ultima data_entrata, o per ordinare iniziando con l'ultimo_data inserito?

SELECT report_id, computer_id, date_entered 
FROM reports 
GROUP BY computer_id 
ORDER BY date_entered DESC 
-- LIMIT 1 -- uncomment to only show the last date. 
+2

Quando id fare questo, ottengo il torto REPORT_ID. Ho controllato la dichiarazione con un WHERE computer_id = 30. Il risultato è stato il primo report_id di tutti i report_id trovati in combinazione con l'ultima data_entered – poetter747

3

accordig a questo: https://bugs.mysql.com/bug.php?id=54784 fusione come char dovrebbe fare il trucco:

SELECT report_id, computer_id, MAX(CAST(date_entered AS CHAR)) 
FROM reports 
GROUP BY report_id, computer_id 
+0

Questo ti darà la data massima, ma non necessariamente gli altri valori della stessa riga. – Vincent

0
SELECT report_id, computer_id, date_entered 
FROM reports 
WHERE date_entered = (
    SELECT date_entered 
    FROM reports 
    ORDER date_entered 
    DESC LIMIT 1 
) 
+1

Grazie per questo snippet di codice, che potrebbe fornire un aiuto limitato e immediato. Una spiegazione appropriata [migliorerebbe notevolmente] (// meta.stackexchange.com/q/114762) il suo valore a lungo termine mostrando * perché * questa è una buona soluzione al problema e lo renderebbe più utile ai futuri lettori con altre domande simili. Per favore [modifica] la tua risposta per aggiungere qualche spiegazione, incluse le ipotesi che hai fatto. –

Problemi correlati