PDA

View Full Version : [SQL] query annidata con max


Abdujaparov
13-03-2008, 14:16
Salve a tutti sto cercando di creare una query sql da sottoporre a mysql.
In pratica ho una tabella con tre colonne: user_id, item_id, preference, la chiave è la coppia (user_id, item_id).
Dalla tabella prendo tutti gli user_id distinti con item_id diverso da un valore X, prendo tutti gli user_id distinti, della stessa tabella, che hanno item_id=Y e che sono inclusi nella query precedente.
Ora tra questi user_id vorrei aver tornare indietro quelli che hanno il valore massimo nel campo preference.

La prima parte della query l'ho scritta in questo modo:

select distinct user_id from taste.taste_preferences_20k t where item_id=334 and user_id in (SELECT distinct user_id FROM taste.taste_preferences_20k t where item_id!=20)


La seconda parte della query non so come scriverla e non so neanche se questo pezzo di sql faccia al caso mio perchè , per esempio quello che voglio ottenere è questo:

L'utente o gli utenti che hanno dato il punteggio più alto (il numero nella colonna preference) all'item 334 (contenuto in item_id) ma che non hanno mai utilizzato l'item 20 (quindi non hanno item_id=20).

Con quel pezzo di queri ottengo tutti gli utenti che hanno item_id=334 e non item_id=20 ora però sorgono tutti i problemi.

Io ho provato a scrivere la query integralmente in questo modo:

select user_id, item_id, max(preference)from taste.taste_preferences_20k t where user_id in ( select distinct user_id from taste.taste_preferences_20k t where item_id=334 and user_id in (SELECT distinct user_id FROM taste.taste_preferences_20k t where item_id!=20) ) and item_id=334 group by user_id;


Però quello che ottengo è questo:

102 334 2
13 334 1
140 334 2
173 334 4
177 334 3
181 334 1
214 334 3
260 334 5
3 334 3
49 334 4
69 334 3
7 334 5
94 334 3


Cosa molto diversa da quello che voglio ottenere io cioè, le sole righe:

260 334 5
7 334 5


Dove la prima colonna è user_id, la seconda item_id, la terza preference.

Come devo modificare la mia query?
Grazie a tutti.
Ciao ciao.

gugoXX
13-03-2008, 20:34
Ciao.
Potresti spiegarci cosa avresti voluto fare, invece di cosa hai fatto?
Ovvero, di cosa hai bisogno?

Hardware Upgrade Forum Database Error
Database Error Database error
The Hardware Upgrade Forum database has encountered a problem.

Please try the following:
  • Load the page again by clicking the Refresh button in your web browser.
  • Open the www.hwupgrade.it home page, then try to open another page.
  • Click the Back button to try another link.
The www.hwupgrade.it forum technical staff have been notified of the error, though you may contact them if the problem persists.
 
We apologise for any inconvenience.