2013-04-06 11 views
7

ho queste tabelle:SQL unirsi a sinistra ottenere MAX (data)

  • preavviso
    • id INT
    • CDate DATETIME
    • ...

  • tema
    • id
    • nome

  • notice_theme
    • id_notice
    • id_theme

voglio ottenere le ultime comunicazioni per ogni tema.

SELECT id_theme, n.id 
FROM notice_theme 
LEFT JOIN (
    SELECT id, cdate 
    FROM notice 
    ORDER BY cdate DESC 
) AS n ON notice_theme.id_notice = n.id 
GROUP BY id_theme 

Il risultato non è buono. Un'idea ? Grazie.

+1

Dov'è il tuo MAX (data)? – hjpotter92

+0

Non è garantito che l'ordine di una tabella unita venga conservato. Metti l'ORDER BY nella selezione esterna. – flup

+0

È necessario aggiungere Max (n.cdate) – Rohit

risposta

6

Ci sono tanti modi per risolvere questo problema ma sono abituato a farlo in questo modo. È necessaria una subquery aggiuntiva per calcolare separatamente l'ultima cDate per ogni ID.

SELECT a.*, c.* 
FROM theme a 
     INNER JOIN notice_theme b 
      ON a.ID = b.id_theme 
     INNER JOIN notice c 
      ON b.id_notice = c.ID 
     INNER JOIN 
     (
      SELECT a.id_theme, MAX(b.DATE_CREATE) max_date 
      FROM notice_theme a 
        INNER JOIN notice b 
         ON a.ID_Notice = b.ID 
      GROUP BY a.id_theme 
     ) d ON b.id_theme = d.id_theme AND 
       c.DATE_CREATE = d.max_date 
+1

Grazie per la risposta, con la query (@JW): > id_theme ---- id_notice ---- date_create > 2 --------- --2 ------------ 2013-03-31 09:18:21 > 4 ----------- 2 ---------- --2013-03-31 09:18:21 > 1 ----------- 7 ------------ 2013-03-31 23:27:28 > 2 ----------- 7 ------------ 2013-03-31 23:27:28 > 4 ----------- 11 ----------- 2013-02-16 04:40:21 > 5 ----------- 12 ----------- 2013- 02-05 20:18:21 > 4 ----------- 13 ----------- 2013-03-31 23:27:28 > 2 --- -------- 14 ----------- 2013-03-15 20:18:21 E con un GROUP BY a.id, ho lo stesso problema con la mia query:/ – user2252137

+0

puoi fornire record di esempio con il tuo risultato scaduto? –

+0

http://www.2shared.com/document/nJNTNfCz/example.html – user2252137