SQL query at least one of something

前端 未结 6 695
鱼传尺愫
鱼传尺愫 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:27

    The correct answer for your question as stated is OMG Ponies's answer, WHERE EXISTS is more descriptive and almost always faster. But "SELECT NULL" looks really ugly and counterintuitive to me. I've seen SELECT * or SELECT 1 as a best practice for this.

    Another way, in case we're collecting answers:

    SELECT u.id 
    FROM users u 
         JOIN posts p on u.id = p.user_id
    WHERE p.rating > 10
    GROUP BY u.id
    HAVING COUNT(*) > 1
    

    This could be useful if it's not always 1 you're testing on.

提交回复
热议问题