获取与同一表中的另一个属性匹配的所有行

时间:2014-12-30 23:03:47

标签: mysql

我有这个表(称为posts):

+---------+----------+---------+
| post_id | reply_to | user_id |
+---------+----------+---------+
|       1 |        0 |       1 |
|       2 |        0 |       1 |
|       3 |        2 |       2 |
|       4 |        1 |       3 |
|       5 |        3 |       2 |
+---------+----------+---------+

如何选择回复user_id = 1帖子的所有帖子?

结果表应如下所示:

+---------+----------+---------+
| post_id | reply_to | user_id |
+---------+----------+---------+
|       3 |        2 |       2 |
|       4 |        1 |       3 |
+---------+----------+---------+

2 个答案:

答案 0 :(得分:1)

这是快速变体:

select *
from posts
where reply_to in (select post_id from posts where user_id = 1);

因此,内部查询选择来自用户的所有帖子,外部查询选择对这些帖子的所有直接回复

答案 1 :(得分:0)

使用self Join

SELECT b.post_id,
       b.reply_to,
       b.user_id
FROM   Posts a
       JOIN Posts b
         ON a.post_id = b.reply_to
WHERE  a.user_id = 1 

或使用Exists运算符

SELECT *
FROM   Posts p
WHERE  EXISTS (SELECT 1
               FROM   Posts p1
               WHERE  p1.user_id = 1
                      AND p.reply_to = p1.post_id);