SQL 中的排除语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1693457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:19:08  来源:igfitidea点击:

Exclude Statement in SQL

sqldatabase

提问by Rohan

How to exclude data from an SQL database using an SQL statement? My situation is I have a user login to their profile page where they will be able to friend people. I want to display all users except themselves that are found in the SQL database.

如何使用 SQL 语句从 SQL 数据库中排除数据?我的情况是我有一个用户登录到他们的个人资料页面,在那里他们可以与人交朋友。我想显示在 SQL 数据库中找到的除自己以外的所有用户。

回答by Russ Cam

Maybe just

也许只是

SELECT *
FROM 
    Users
WHERE
    UserId <> @ThisUserId

Or using a Difference Union (The EXCEPTkeyword in SQL Server, not sure about other RDBMS implementations)

或者使用Difference Union(EXCEPTSQL Server中的关键字,其他RDBMS实现不确定)

SELECT *
FROM 
    Users

EXCEPT

SELECT *
FROM 
    Users
WHERE
    UserId = @ThisUserId

回答by AJ.

How about:

怎么样:

SELECT * FROM people WHERE person_id != $current_user_id

回答by alk

Yes I know Im late with this one.

是的,我知道我迟到了这个。

Anyhow as I stumpled over those comments here while looking for an answer to a question similare to the one ask here ("how to exlcude data from a query") I was a bit confused.

无论如何,当我在寻找与这里提出的问题(“如何从查询中排除数据”)类似的问题的答案时,我在这里绊倒了这些评论,我有点困惑。

Confused because I knew the answer I was looking for was not only more simple, but even more elegant then the ones proposed here. I once knew the answer, but forgot it. I came here because I was too lazy to remember...

困惑,因为我知道我正在寻找的答案不仅更简单,而且比这里提出的更优雅。我曾经知道答案,但忘记了。我来这里是因为我懒得记...

So I struggled hard to remember the easy solution and then it came back to my mind.

所以我努力地想记住这个简单的解决方案,然后它又回到了我的脑海中。

So assume you have the two tables "Email" and "UnwantedEmail" with both carring the one column "Address". The query to only get the wanted email addresses, those addresses which are in "Email" but not in "UnwantedEmail" could look like the following:

因此,假设您有两个表“Email”和“UnwantedEmail”,都带有一列“地址”。仅获取想要的电子邮件地址的查询,那些在“电子邮件”中但不在“UnwantedEmail”中的地址可能如下所示:

SELECT Email.Address FROM UnwantedEmail
RIGHT JOIN Email ON UnwantedEmail.Address=Email.Address
WHERE UnwantedEmail.Address Is Null;

回答by Saar

select * from Foo where UserName not in ('Rohan', 'Rohan's friend', .....)

Is this useful?

这有用吗?

回答by jay

If you know what that user's unique ID is you could use something like this for example:

如果您知道该用户的唯一 ID 是什么,则可以使用以下内容,例如:

SELECT * FROM usertable WHERE id!='myuserid'

What I do with one of my authentication scripts is store the information for the person that is currently logged in in a variable so it would look like this in PHP:

我用我的一个身份验证脚本做的是将当前登录的人的信息存储在一个变量中,所以它在 PHP 中看起来像这样:

SELECT * FROM usertable WHERE id!='check(id)'