检查行是否在加入时具有特定子项

时间:2015-04-08 14:13:01

标签: php mysql sql join left-join

我想创建一个SQL,让用户获得名称为Mark的用户,并且是包含ids 13的帖子的作者。

注意:我不知道需要检查多少帖子。因此可能需要使用PHP生成SQL查询的那一部分。

怎么办呢?

用户表:

+----+----------+
| id |   name   |
+----+----------+
|  1 | Mark     |
|  2 | John Doe |
+----+----------+

帖子表

+----+-------------+-------------+
| id |    text     |  author_id  |
+----+-------------+-------------+
|  1 | First Post  |           1 |
|  2 | Second Post |           2 |
|  3 | Last Post   |           1 |
+----+-------------+-------------+

这只是一个使用示例,而不是真实数据。

注意:我知道如何检查用户是否是一个帖子的作者,而不是同一行中的多个。基本上我需要帮助,我想它必须是left join

为了检查名为Mark的用户并检查他是否是帖子ID 1的作者,我执行以下操作:

SELECT users.*
FROM users
INNER JOIN posts
    ON users.id = posts.author_id
WHERE
    users.name = 'Mark'
    &&
    posts.author_id` = 1

4 个答案:

答案 0 :(得分:1)

我刚从id中选择了users。如果您需要更多列,只需将其添加到selectgroup by子句。

SELECT users.id
FROM users
INNER JOIN posts ON users.id = posts.author_id
WHERE users.name = 'Mark'
AND posts.author_id in (1,3)
GROUP BY users.id
HAVING count(distinct posts.author_id) = 2

答案 1 :(得分:1)

使用子查询仅查找同时包含1和3的用户:

SELECT users.*
FROM users
WHERE users.name = 'Mark'
  and 2 = (select count(distinct posts.id)
           where users.id = posts.author_id
             and posts.id IN (1,3))

答案 2 :(得分:0)

SELECT users.name,posts.posts,posts.authorid FROM users INNER JOIN帖子ON users.id = posts.authorid where posts.authorid = 1

答案 3 :(得分:0)

您需要使用HAVING子句来实现预期结果:

SELECT users.name
  FROM users
    INNER JOIN posts
        on users.id = posts.author_id
 WHERE users.name = 'Mark'
 GROUP BY users.name
 HAVING COUNT(posts.author_id) > 1
相关问题