mysql: Come ISCRIVERSI a un tavolo ma limitare l'unione a 1 risultato con il voto o il conteggio più alti?

StackOverflow https://stackoverflow.com/questions/1425894

  •  07-07-2019
  •  | 
  •  

Domanda

Ho 2 tavoli. Uno è elementi e un altro è voti per quegli elementi.

Items table has: |item_id|name|post_date
Votes table has: |votes_id|item_id|answer|total_yes|total_no

Quello che voglio fare è mostrare tutti gli elementi in base a post_date e mostrare la risposta nella tabella dei voti con il più alto totale_yes. Quindi voglio mostrare solo una SINGOLA risposta dalla tabella dei voti con il punteggio total_yes più alto.

Ci stavo provando:

SELECT a.*, b.* FROM Items a
INNER JOIN Votes b ON a.item_id = b.item_id
GROUP by a.item_id
ORDER by a.post_date DESC, b.total_yes DESC

Ma questo non funziona.

Il risultato che vorrei vedere è:

<item><answer><yes votes>
Buick | Fastest | 2 yes votes
Mercedes | Shiny | 32 yes votes
Honda | Quick | 39 yes votes

Qualsiasi aiuto è apprezzato!

È stato utile?

Soluzione

SELECT a.*, b.*
  FROM Items a
       LEFT JOIN Votes b on a.item_id = b.item_id
                         and b.total_yes = (select max(total_yes) 
                                              from Votes v 
                         where v.item_id = a.item_id)
ORDER BY a.post_date DESC, b.total_yes DESC

N.B .: se hai per un oggetto 2 risposte con lo stesso total_yes = max, avrai 2 righe per quell'elemento.

Altri suggerimenti

aggiungi LIMIT 1 alla fine della tua query :)

che richiederà solo un record, ma al momento stai ordinando prima la data, quindi otterrai il voto più alto per l'ultima data votata. È quello che vuoi?

Se desideri il voto totale più alto, indipendentemente da ciò, devi prima ordinarlo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top