Re: Legal sql

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Gerard,

> Im looking for another opinion on an sql statement.
> SELECT sc.col1 FROM search s, search_content sc WHERE s.word = 'mysql' >
AND s.wid = sc.wid OR s.word = 'apache' AND s.wid = sc.wid;
> I had to use "s.wid = sc.wid" twice in the sql for the query to work
> properly.  Is this the legal, correct way to do so.


You're perfectly legal, but have become tangled up in the rules of operator
precedence. In fact MySQL's optimiser probably takes care of it all for you.

Precedence says that if there are multiple operators they will be executed
from left to right, unless one is considered more important than the other,
eg * precedes +, or in your case, AND precedes OR.

To override precedence, or merely to help with readability, one may employ
parentheses - calculations within parentheses are performed first. Thus the
code becomes:

WHERE ( s.word = 'mysql' AND s.wid = sc.wid )
   OR ( s.word = 'apache' AND s.wid = sc.wid );

Now one can apply Boolean algebra and rationalise the apparent duplication:

WHERE s.wid = sc.wid
   AND ( s.word = 'mysql' OR s.word = 'apache' );

As to which is 'right' and which 'wrong', let me ask: which one do you find
most readable?

Regards,
=dn


-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux