SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict bkennedy's Avatar
    Join Date
    Aug 2004
    Location
    michigan
    Posts
    251
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    query: and/or clauses together?

    Hi. I want to do a query that looks (logically) like this...

    Code:
    select part, description from table 
    WHERE (part_no like 'string1' OR description like 'string1') 
    AND (part_no like 'string2' OR description like 'string2')
    Basically, I'm trying (with php) to refine search results, and this is the only way I know of to search within results of a query. I have the logistics of getting the original search term, but adding a term to it then searching multiple fields is tricky for me.
    I want it to do the original search (for 'string1') then narrow the results by using the "AND".

    I can't use parenthesis like that can I?
    Any help would be much appreciated.
    ----------------
    bob.kennedy
    ----------------

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,347
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by bkennedy
    I can't use parenthesis like that can I?
    yes, you sure can, and in fact it is essential that you do

    compare what you have with this --
    Code:
     WHERE part_no like 'string1' 
        OR (
           description like 'string1'
       AND part_no like 'string2'
           )
        OR description like 'string2'
    the above is actually the way it would be evaluated if you had no parentheses at all, since ANDs take precedence over ORs

    any time you mix ANDs and ORs, you should always use parentheses to ensure it does exactly what you want
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Addict bkennedy's Avatar
    Join Date
    Aug 2004
    Location
    michigan
    Posts
    251
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a ton!
    ----------------
    bob.kennedy
    ----------------


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •