Exclusionary SELECT in SQL

Reply

Join Date: Jun 2005
Posts: 14
Reputation: aiden is an unknown quantity at this point 
Solved Threads: 0
aiden aiden is offline Offline
Newbie Poster

Exclusionary SELECT in SQL

 
0
  #1
Mar 8th, 2006
Hi,

While I'm not entirely new with SQL, I am not by any means highly knowledgable.

I'm attempting to write a SQL statement to do the following, and having no luck:

Assumptions:
There is only one table, with several fields of metadata including the following.

1 field (integer) that indicates which section the table element is in. (e.g., 1="Illustrations Gallery" 2="Painting Gallery") Call this Field A.

1 field that can be NULL, or can contain the id (pkey) of another entry in the same table indicating a link between them. Call this Field B.

Field B can only contain links (primary keys) from elements that have a specific value of Field A.

I want to select the IDs of "eligable" elements. That is, rows who have the right value of A, and are not present in any other row's value of B.

Therefore: I need a query that says, essentially -

SELECT * from `table` where `A`=X AND `id`=(Doesn't Exist Anywhere in B);

Any ideas?

--
Aiden
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 354
Reputation: Troy is an unknown quantity at this point 
Solved Threads: 5
Troy's Avatar
Troy Troy is offline Offline
Posting Whiz

Re: Exclusionary SELECT in SQL

 
0
  #2
Mar 10th, 2006
What version of MySql? 4.1 and newer support subqueries. If your version support subqueries, you can do something like this:
  1. SELECT *
  2. FROM mytable
  3. WHERE a = 147
  4. AND id NOT IN (SELECT b FROM mytable)

Otherwise, try this:
  1. SELECT t1.*
  2. FROM mytable t1
  3. LEFT JOIN mytable t2 ON t1.id = t2.b
  4. WHERE t1.a = 147
  5. AND t2.b IS NULL

That second query was not fun! I got help at this URL:
http://dev.mysql.com/doc/refman/4.1/...ubqueries.html
Troy Wolf is the author of SnippetEdit. "Website editing as easy as it gets." IX Web Hosting
Reply With Quote Quick reply to this message  
Join Date: Feb 2002
Posts: 12,040
Reputation: cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light 
Solved Threads: 127
Administrator
Staff Writer
cscgal's Avatar
cscgal cscgal is offline Offline
The Queen of DaniWeb

Re: Exclusionary SELECT in SQL

 
0
  #3
Mar 10th, 2006
The second query is the way I am used to doing it.
Dani the Computer Science Gal
Follow my Twitter feed! twitter.com/daniweb
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC