MySQL 当一个字段不等于另一个字段时,带有条件的 SQL 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11241958/
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-08-31 13:59:23  来源:igfitidea点击:

SQL query with condition when one field not equal to another

mysqlsql

提问by Vitaly Lebedev

Let's say we have fields: id | content | updateTime | creationTime

假设我们有字段: id | 内容 | 更新时间 | 创建时间

When insertion done both updateTime and creationTime get filled with current time. On update only updateTime field get changed. When I need to find all data created on '2012-06-28' I simply use:

插入完成后, updateTime 和 creationTime 都会填充当前时间。更新时只有 updateTime 字段会发生变化。当我需要查找在“2012-06-28”上创建的所有数据时,我只需使用:

SELECT id, content FROM tbl WHERE creationTime LIKE '2012-06-28%'`

But to get all data that was updated excluding created data I need to use something like this:

但是要获取不包括创建的数据的所有更新数据,我需要使用以下内容:

SELECT id, content FROM tbl WHERE creationTime LIKE '2012-06-28%' AND creationTime != updateTime

This can't work, obviously. Though I could find all updated data by comparing values of two 'time' collumns inside php, I'd still love to do it inside query.

这显然行不通。虽然我可以通过比较 php 中两个“时间”列的值来找到所有更新的数据,但我仍然喜欢在查询中进行。

UPD: Well, it turns out that I was absolutely unaware that sql allows not only compare value of a field with a given variable, number... but also it can compare value of one field with another.

UPD:好吧,事实证明我完全不知道 sql 不仅允许将字段的值与给定的变量、数字进行比较……而且它还可以将一个字段的值与另一个进行比较。

回答by DonCallisto

Use <>instead !=(that isn't compatible with some DMBS)

使用<>替代!=(即不兼容一些DMBS)

So

所以

SELECT id, content 
FROM tbl 
WHERE creationTime LIKE '2012-06-28%' AND creationTime <> updateTime

If you want some documentation you can find here

如果你想要一些文档,你可以在这里找到

However, your query have to work properly with !=

但是,您的查询必须与 !=

回答by bluehallu

Your query is correct (on mySQL1), don't know why would you think otherwise

您的查询是正确的(在 mySQL1 上),不知道您为什么会这么想

1 <>is the SQL operator for not equal. Some implementations of it (PostgreSQL or MySQL for instance), however, accept !=too. It is a good practice to always use <>to avoid problems if you ever use your code on a different database.

1<>是不等于的 SQL 运算符。但是,它的一些实现(例如 PostgreSQL 或 MySQL)!=也接受。<>如果您曾经在不同的数据库上使用您的代码,那么始终使用它是一种很好的做法,以避免出现问题。

回答by Shaikh Farooque

Only change the not operator from !=to <>

仅将 not 运算符从 更改!=<>

SELECT id, content FROM tbl WHERE creationTime LIKE '2012-06-28%' AND creationTime <> updateTime