SQL query at least one of something

前端 未结 6 680
鱼传尺愫
鱼传尺愫 2021-02-01 07:33

I have a bunch of Users, each of whom has many Posts. Schema:

Users: id
Posts: user_id, rating

How do I find all Users who have at least one po

6条回答
  •  伪装坚强ぢ
    2021-02-01 08:09

    To find all users with at least one post with a rating above 10, use:

    SELECT u.*
      FROM USERS u
     WHERE EXISTS(SELECT NULL
                    FROM POSTS p
                   WHERE p.user_id = u.id
                     AND p.rating > 10)
    

    EXISTS doesn't care about the SELECT statement within it - you could replace NULL with 1/0, which should result in a math error for dividing by zero... But it won't, because EXISTS is only concerned with the filteration in the WHERE clause.

    The correlation (the WHERE p.user_id = u.id) is why this is called a correlated subquery, and will only return rows from the USERS table where the id values match, in addition to the rating comparison.

    EXISTS is also faster, depending on the situation, because it returns true as soon as the criteria is met - duplicates don't matter.

提交回复
热议问题