views:

51

answers:

2

Tables


file_logs

  • file_id
  • user_id

files

  • id
  • name
  • etc ...

published_ratings

  • author_id
  • file_id
  • comment
  • etc ...

Scenario


I am creating a download log and need to display which files a user has rated as well as the unrated ones, this has to be done with 1 query.

I already took a crack at this,

SELECT 
  files.*, 
  IF(file_logs.user_id = published_file_ratings.author_id, TRUE, FALSE) AS rated
FROM file_logs
JOIN files
  ON file_logs.file_id = files.id
LEFT JOIN published_file_ratings
  ON file_logs.file_id = published_file_ratings.file_id
WHERE file_logs.user_id = 8
GROUP BY id

The problem with this query is that if an incorrect user came up first the results would be wrong.

The result should be an array of all the files the user has downloaded with a "rated" column depicting if they've rated the file or not.

Any help is really appreciated.

+2  A: 

you need to add AND file_logs.user_id = published_file_ratings.author_id to your JOIN clause

you can also change your IF statement to IF(ISNULL(published_file_ratings.author_id), FALSE, TRUE)

also, you can now remove the GROUP BY to hide the multiple users. its use here in that manner is incorrect.

longneck
Perfect, thank you *very* much.
The Pixel Developer
A: 

You can't do "GROUP BY id" and then select the rest of the columns. This doesn't make sense. Any other DB than MySQL would throw an error if you tried to select columns that weren't either in the Group By, or contained within an aggregate statement like SUM(ColName).

Kibbee