简体   繁体   English

SQL LEFT JOIN where子句与IN比较

[英]SQL LEFT JOIN where clause with IN comparison

May have inadvertently stumbled onto a good SQL test question. 可能无意间偶然发现了一个好的SQL测试问题。

  • I have a table with let's say ~100 usernames. 我有一个表,可以说约100个用户名。
  • I have a set of 10 possible usernames { aname, bname, cname, dname, ... } 我有一组10个可能的用户名{aname,bname,cname,dname,...}

If I do: 如果我做:

SELECT user.username FROM user WHERE user.username IN ('aname', 'bname', 'cname',...);

I get a list of usernames selected for, minus the ones not found in the table, grand. 我得到了一个选定的用户名列表,减去表中未找到的用户名。

What I actually want, is a list of the ones NOT found in the table. 我真正想要的是列表中未找到的列表。

If the WHERE...IN clause list was a table, I'd just LEFT JOIN it onto the user table and filter for NULLs . 如果WHERE...IN子句列表是一个表,则只需将其LEFT JOIN移到用户表上并过滤NULLs

Is there a way to do this without making a temp table and left joining that to the user table? 有没有一种方法可以不创建临时表并将其连接到用户表? I guess, sort of a left join of the user table to the WHERE...IN clause? 我猜是用户表与WHERE...IN子句的左连接?

I've never done or seen it, but perhaps it exists. 我从未看过它,但是也许它存在。

You can do this with a derived table and a left join : 您可以使用派生表和left join来做到这一点:

SELECT l.name
FROM (SELECT 'aname' as name UNION ALL
      SELECT 'bname' UNION ALL
      SELECT 'cname' UNION ALL
      . . .
     ) l LEFT JOIN
     user u
     ON u.username = l.name
WHERE u.username IS NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM