在 SQL 中,如何执行“减法”?手术?

发布于 2024-10-15 07:53:21 字数 90 浏览 3 评论 0原文

假设我有两个表,它们都有用户 ID。我想要执行一项操作,返回表 1 中不在表 2 中的所有用户 IDS。我知道必须有一些简单的方法来执行此操作 - 谁能提供一些帮助?

Suppose I have two tables, which both have user ids. I want to perform an operation that would return all user IDS in table 1 that are not in table 2. I know there has to be some easy way to do this - can anyone offer some assistance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

千纸鹤带着心事 2024-10-22 07:53:21

虽然速度很慢,但通常可以通过“not in”之类的命令来完成此操作。 (各种 RDBMS 系统中还有其他函数可以以更好的方式执行此操作,例如 Oracle 有一个“exists”子句可用于此目的。

但您可以说:

select id from table1 where id not in (select id from table2)

Its slow, but you can normally accomplish this with something like 'not in'. (There are other functions in various RDBMS systems to do this in better ways, Oracle for instance has a 'exists' clause that can be used for this.

But you could say:

select id from table1 where id not in (select id from table2)
空袭的梦i 2024-10-22 07:53:21

有几种方法可以做到这一点。这是使用 NOT EXISTS 的一种方法:

SELECT userid
FROM table1
WHERE NOT EXISTS
(
    SELECT *
    FROM table2
    WHERE table1.userid = table2.userid
)

这是使用联接的另一种方法:

SELECT table1.userid
FROM table1
LEFT JOIN table2
ON table1.userid = table2.userid
WHERE table2.userid IS NULL

最快的方法取决于数据库。

There are a few ways to do it. Here's one approach using NOT EXISTS:

SELECT userid
FROM table1
WHERE NOT EXISTS
(
    SELECT *
    FROM table2
    WHERE table1.userid = table2.userid
)

And here's another approach using a join:

SELECT table1.userid
FROM table1
LEFT JOIN table2
ON table1.userid = table2.userid
WHERE table2.userid IS NULL

The fastest approach depends on the database.

此岸叶落 2024-10-22 07:53:21

一种方法是使用 EXCEPT(如果您的 TSQL 方言支持)。相当于执行左连接和空测试

One way is to use EXCEPT if your TSQL dialect supports it. It is equivalent to performing a left join and null test

恋你朝朝暮暮 2024-10-22 07:53:21
SELECT user_id FROM table1 LEFT JOIN table2 ON table1.user_id = table2.user_id WHERE table2.user_id IS NULL;
SELECT user_id FROM table1 LEFT JOIN table2 ON table1.user_id = table2.user_id WHERE table2.user_id IS NULL;
垂暮老矣 2024-10-22 07:53:21

如果是的话
SQL Server:

SELECT id FROM table1
EXCEPT 
SELECT id FROM table2

Oracle:

SELECT id FROM table1
MINUS
SELECT id FROM table2

休息:我不确定......

If it is
SQL Server:

SELECT id FROM table1
EXCEPT 
SELECT id FROM table2

Oracle:

SELECT id FROM table1
MINUS
SELECT id FROM table2

Rest: Am not sure....

无悔心 2024-10-22 07:53:21

试试这个:

SELECT id FROM table1 WHERE id NOT IN
(
    SELECT id FROM table2
)

Try this:

SELECT id FROM table1 WHERE id NOT IN
(
    SELECT id FROM table2
)
久隐师 2024-10-22 07:53:21
select ID from table1
where ID not in (select ID from table2)
select ID from table1
where ID not in (select ID from table2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文