简体   繁体   中英

Does row exist is another table?

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM