Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2004
    Posts
    1

    Unanswered: Rewrite query with EXISTS clause

    Hi!

    I have to rewrite a query with EXISTS clause for MySQL 3.23 since I cannot use MySQL 4.1.
    The purpose of the query was to find all records from table MAIN that are annotated by a given set of numbers (number1, number2, ...). I have two tables: MAIN(ID, NAME) and A(ID, NUMBER) that stores the annotation relationship. The original query was:

    SELECT NAME FROM MAIN WHERE
    EXISTS (SELECT * FROM A WHERE MAIN.ID=A.ID AND NUMBER='number1') AND
    EXISTS (SELECT * FROM A WHERE MAIN.ID=A.ID AND NUMBER='number2') AND ... so on for every number.

    Is there any other way to write this query? Without the EXISTS clause?

    Thanks,
    Mike

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    whoever wrote that query was missing something very obvious
    Code:
    select NAME 
      from MAIN 
    inner
      join A
        on MAIN.ID 
         = A.ID 
     where NUMBER
        in ('number1','number2',...)
    group
        by NAME
    Edit: ooops those were ANDs joining the EXISTs clauses, not ORs

    okay, forget the above, use this:
    Code:
    select NAME 
      from MAIN 
    inner
      join A as A1
        on MAIN.ID  = A1.ID 
       and A1.NUMBER = 'number1'
    inner
      join A as A2
        on MAIN.ID  = A2.ID 
       and A2.NUMBER = 'number2'
    ...
    group
        by NAME
    Last edited by r937; 06-01-04 at 10:01.
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

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