问题
Which of the two (semantically equivalent) ways is preferable to test for inequality?
'foo' != 'bar'
(exclamation mark and equals sign)'foo' <> 'bar'
(less than and greater than chevron symbols together)
The MySQL documentation clearly indicates that there is no difference between them and yet some people seem to be attached to only doing it one way or the other. Maybe this is just another pointless vi vs. emacs debate but when other people are reading your code (and therefore your queries), it's useful to maintain some consistency.
<>
looks a lot like <=>
which is a very underused operator but could perhaps lead to confusion at a quick glance since the two are nearly opposite (except for the obvious NULL
cases).
回答1:
<> should be preferred, all things being equal, since it accords with the sql standard and is technically more portable...
!= is non-standard, but most db's implement it.
sql:2008 grammar:
<not equals operator> ::=
<>
回答2:
It's obvious.
The ! character is on the North West corner of US keyboards.
Microsoft headquarters are in the North West corner of the US.
So. <>
is a nod to Microsoft.
!=
is a rejection of Microsoft.
It's a secret political code.
回答3:
<> is the only one in the SQL-92 standard.
回答4:
DBA's generally like <> and programmers like !=. Just an observation :-)
回答5:
They are the same, it is purely preference.
This should give you a good idea
Operators
!= (Not Equal To) Not equal to (not SQL-92 standard)
<> (Not Equal To) Not equal to
回答6:
The <>
operator is the one that is in the SQL standard, so most people that know SQL will be accustomed to it, or at least aware of it. I myself wasn't even aware of that the !=
operator was also available in some SQL dialects until recently.
As you noticed, people tend to use only one or the other, and that is a good approach, at least on a project-by-project basis. Whichever you choose to use, be consistent.
来源:https://stackoverflow.com/questions/2066987/using-the-correct-or-preferable-not-equal-operator-in-mysql