0

我正在寻找适合这种情况的最佳 MySQL 查询:

我列出了成员的最后 10 个帖子。

table for posts:
post_id | uid | title | content | date

会员可以订阅其他会员帖子,使帖子列在同一个列表中(按日期排序 - 同一个表)

因此,可以选择用户 ID X 和用户 ID Y 的最后帖子但我想允许成员禁用显示某些帖子(他不想显示的帖子)。

我的问题是:我怎样才能使 MySQL 尽可能简单?...我想到了第二个表,我在其中放置了用户不想要的帖子 ID:

table postdenied
uid | post_id

然后进行如下选择:

select * from posts as p where not exists (select 1 from postdenied as d where d.post_id = p.post_id and d.uid = p.uid) order by date DESC limit 10

我是正确的?还是有更好的东西?

谢谢

4

2 回答 2

3

如果我理解正确,该posts.uid列存储海报的 ID。并且postdenied.uid存储不想看到某个帖子的用户的 ID。

如果上述假设是正确的,那么您的查询就很好,除了您不应该加入uid列,只加入post_id那些。并且您应该有一个参数或常量,@X即您想要显示所有帖子的用户的用户 ID(如下面的代码所示)——除了那些他“拒绝”的帖子:

select p.* 
from posts as p 
where not exists 
      (select 1 
       from postdenied as d 
       where d.post_id = p.post_id 
         and d.uid = @X             -- @X is the userID of the specific user
      )                                 
order by date DESC 
limit 10 ;
于 2013-08-05T18:04:03.713 回答
1

实现这一点的另一种方法是使用LEFT JOIN子句。

SELECT * FROM posts AS p 
  LEFT JOIN postdenied as d ON d.post_id = p.post_id and d.uid = p.uid
WHERE d.uid IS NULL
ORDER BY date DESC 
LIMIT 10

我不清楚这是否更适合查询优化器。如果您有大量数据,则可能值得同时测试两个查询并查看一个是否比另一个性能更好。

http://sqlfiddle.com/#!2/be7e3/1

感谢 ypercube 和 Lamak 对我的原始答案的反馈

于 2013-08-05T17:49:29.597 回答