Re: Legal sql

From: Date: Tue, 22 Oct 2002 04:22:20 +0000
Subject: Re: Legal sql
References: 1 2  Groups: php.db 
Request: Send a blank email to php-db+get-22569@lists.php.net to get a copy of this message
Thanks for the reply. The parentheses are noted. Meantime, I did some reading and came up with this -> SELECT sc.col1 FROM search s, search_content sc WHERE s.word IN ('apache', 'mysql') AND s.wid = sc.wid Thanks for the tip. DL Neil wrote:
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
-- Gerard Samuel http://www.trini0.org:81/ http://dev.trini0.org:81/

« previous php.db (#22569) next »