如果用户被阻止,则跳过mysql查询的输出

时间:2014-08-20 08:14:39

标签: mysql sql

我有两张表:questionblock_user

我使用以下查询来获取活动的问题:

SELECT 
    tq.question_id,tq.info,tq.owner_id
FROM
    question as tq
     ..... Other Join .......
     ..... Other Join .......
where
    tq.is_active = '1'

block_user表包含以下字段:id,owner_id,question_id,block_user_id

现在,如果quesNown所有者阻止某些用户,则那些用户无法查看被阻止的问题。

EXA:

假设表question包含以下数据:

  

question_id owner_id info

     

1 ....................... 1 ................你好   2 ....................... 1 ................嗨   3 ....................... 1 ................欢迎你   4 ....................... 1 .................演示
  5 ....................... 1 ................ Stack Over flow

假设表block_user包含以下数据:

  

id owner_id question_id block_user_id

     

1 ...... 1 ................. 2 ..................... 。2
  2 ...... 1 ................. 4 ....................... 2

所以,我想要做的是如果用户2想要提取问题,那么他就能看到question_id:1,3,5
他无法看到question_id:2,4,因为在这个问题中他被封锁了。

我使用以下但不起作用:

SELECT 
    tq.question_id,tq.info,tq.owner_id
FROM
    question as tq
        join
    block_user as tbu ON tq.user_id not in (tbu.user_id)
    and tq.question_id not in (tbu.question_id)
    and '2' not in (tbu.block_user_id)
     ..... Other Join .......
     ..... Other Join .......
where
    tq.is_active = '1'

那么如何在一个查询中实现这一点呢? 提前致谢。

2 个答案:

答案 0 :(得分:2)

这是我通常进行此类查询的方式。我更喜欢LEFT JOIN并丢弃那些匹配的行。您也可以使用子查询,但这通常可以获得更快的结果。

SELECT 
    tq.question_id,tq.info,tq.owner_id
FROM question as tq
    LEFT JOIN block_user as bu 
         ON tq.question_id = bu.question_id AND bu.block_user_id = '2'
     ..... Other Join .......
     ..... Other Join .......
WHERE tq.is_active = '1'
  AND bu.question_id IS NULL

答案 1 :(得分:1)

SELECT 
    tq.question_id,tq.info,tq.owner_id
FROM
    question as tq
where
    tq.is_active = '1'
    and
    tq.question_id not in (SELECT bu.question_id from block_user bu where bu.block_user_id = {YOUR USER ID})