编写 SQL 查询以通过子查询检索数据?

Writing SQL Query to retrieve data via a Subquery?

我需要编写一个查询来检索满足以下条件的值,

Select Users from UserTable that I am (me@gmail.com) not friends with

这是我的 table 格式:

我的电子邮件列在 UserID 中,我的朋友列在 FriendID 列中。我需要 select UserTable 中未在 FriendsTable 中列为好友的用户。似乎是一个简单的查询,但我无法弄清楚。这是我尝试过的:

P.S: 我写这篇文章只是为了澄清,因此我 不想 编写参数化查询。我不打算分发这个。

SELECT * From UserTable  WHERE Email NOT LIKE '% (Select FriendsTable.FriendID From FriendsTable Where FriendsTable.UserID='me@gmail.com') %'  

编辑

jpw 的查询有效。但是,如何从他的解决方案查询中检索随机行?

这行不通:

select TOP 1 * from UserTable where UserTable.Email <> '" + email + "' and Email not in (select case when FriendsTable.UserID = '" + email + "' then FriendsTable.FriendID else UserID end from FriendsTable where '" + email + "' in (UserID, FriendID)); ORDER BY NEWID()

您可以使用 NOT EXISTS 检查 Email 是否不存在于 friends table 中,如下所示

select * from
UserTable ut
where not exists (
select 1 from FriendsTable
where UserID != ut.Email)
and ut.Email = 'me@gmail.com';

另一个解决方案是使用 LEFT JOIN 并选择 NULL like

select ut.*
from UserTable ut
left join FriendsTable ft on ut.Email = ft.UserID
where ft.UserID is null and ut.Email = 'me@gmail.com';

如果您要查找不是单个用户好友的所有用户,请尝试以下操作:

select t.Email
from UserTable as t
left join FriendsTable as f on f.UserID=t.Email
where f.UserID IS NULL and t.Email='me@gmail.com'

如果朋友关系可以双向进行,并且您不仅要排除 email = 'me@gmail.com' 的行,还要排除 FriendID = 'me@gmail.com' 的行,即下面的两行

UserID            FriendID
me@gmail.com      ddaabb@gmail.com
kk@gmail.com      me@gmail.com  

那么此查询将执行此操作:

select * 
from userTable
where Email <> 'me@gmail.com'
  and Email not in (
    select 
      case 
       when UserID = 'me@gmail.com' 
       then FriendID else UserID 
      end 
    from FriendsTable 
    where 'me@gmail.com' in (UserID, FriendID)
  );

即使您只想排除出现在 FriendID 列中的那些用户,这仍然有效,尽管在这种情况下有更好的方法。

使用您的示例数据,结果将是:

kk@gmail.com
yybb@gmail.com

或者你这样做:

select * from
UserTable u
where u.Email <> 'me@gmail.com' and
not exists (
    select 1 from FriendsTable
    where FriendID = u.Email
  );