【问题标题】:Select Users that are not blocked - SQL选择未被阻止的用户 - SQL
【发布时间】:2018-07-26 20:02:03
【问题描述】:

我有一张表用户

  • id
  • 姓名

还有另一个表blocked_users

  • user_id
  • user_blocked_id

当一个用户阻止另一个用户时,将他们的 id 添加到 blocked_users.user_id 和他们在 blocked_users.user_blocked_id 中阻止的用户。

我想从 users 表中选择我的 user.id 未在 blocked_users.user_id 中退出的所有用户(用户我已阻止)或 blocked_users.user_block_id(其他人已阻止我)。所以他们都看不到其他人的信息。

SELECT        a.*
FROM          users a
LEFT JOIN     blocked_users b
ON            b.user_id = a.id
AND           b.user_blocked_id = a.id
WHERE NOT     b.user_id = '$id'
AND NOT       b.user_blocked_id = '$id';

我卡在查询上!

【问题讨论】:

  • 您使用的是哪个DBMS product? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加tag postgresql, oracle, sql-server, db2, ...
  • 如果您使用的是 PHP,您应该将该标签添加到您的问题中。

标签: php mysql sql


【解决方案1】:

使用not exists:

select u.*
from users u
where not exists (select 1
                  from blocked_users bu
                  where bu.user_id = u.id and bu.user_blocked_id = ?
                 ) and
      not exists (select 1
                  from blocked_users bu
                  where bu.user_blocked_id = u.id and bu.user_id = ?
                 );

注意? 的使用。这是为了将参数传递到查询中。这比使用字符串值修改查询要好得多。

【讨论】:

  • 原生SQL中是否存在参数化查询?
  • @GangaiJohann 。 . .几乎所有让应用程序与之对话的数据库都支持参数化查询。
【解决方案2】:

如果您想从 users 表中选择 所有 用户,请使用以下代码:

select u.*
  from users u
 where not exists (select 1
                     from blocked_users bu
                    where bu.user_id = u.id) 
   and not exists (select 1
                     from blocked_users bu
                    where bu.user_blocked_id = u.id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多