If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Rewrite query with EXISTS clause

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 06-01-04, 06:40
xmasam xmasam is offline
Registered User
 
Join Date: Jun 2004
Posts: 1
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
Reply With Quote
  #2 (permalink)  
Old 06-01-04, 08:59
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
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
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book

Last edited by r937; 06-01-04 at 09:01.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On