简体   繁体   中英

What is the difference between keeping column on left of = in sql

I am reading someone else sql and his code was like this

There is view called user_v with column path as Array

select * from user_v where 'USER_TYPE'=path[2]

can't i use

path[2] = 'USER_TYPE'

This is a precaution taken by some programmers in languages where assignment and comparison can be easily confused, such as C or PHP, where the following statement looks innocent:

 if ( $foo = 1 )

but it is actually assigning 1 to $foo , and the if will always evaluate to true (in PHP, at least, where 1 is true). What was meant was if ( $foo == 1 ) .

If you reverse the arguments, the error becomes obvious sooner:

if ( 1 = $foo ) # SYNTAX ERROR
if ( 1 == $foo ) # Desired behaviour

This is sometimes known as "yoda coding", and is in the coding standards of Wordpress, for example .

See also: Why put the constant before the variable in a comparison?

In SQL, there is less chance of such a muddle, since although = can mean either assignment or comparison, there are rarely situations where a typo would select the wrong meaning.

However, if the coding standards for every other language used by a project mandate it, it would make sense to reinforce the habit by also using it in SQL, since I can't think of a specific reason not to write it that way.

完全没有区别。

It's psychology. You would want to read someone else's code out laud and say:

Where my column equals 2.

When you read:

Where 2 equals my column

you have to stop for a while, return, explain it to yourself.

We maintain all of these rules that seem rubish at first glance just to make other people lives easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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