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 > Two table specific join

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-28-04, 09:34
andris2000 andris2000 is offline
Registered User
 
Join Date: Feb 2004
Posts: 4
Two table specific join

Hello everyone

I have two tables in my application:

table_X
+-------+
| a_id | b_id |
+-------+
| 1 | 2 |
| 1 | 3 |
| 2 | 2 |
| 3 | 3 |
| 4 | 1 |
| 4 | 2 |
| 4 | 3 |

table_Z
+-----------------+
| b_id | system_flag |
+----------------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |

In this two tables all table_X records have one or more specific b_id's from another table (table_Z). b_id's in table_Z could be system or not system. What I need is a query that would list all a_id's that does not have any b_id's with system flag. (If a_id has even one b_id that is sytem, it should be not returned).

How can I achieve this ?
Reply With Quote
  #2 (permalink)  
Old 02-28-04, 09:48
aus aus is offline
Registered User
 
Join Date: Oct 2003
Location: Denver, Colorado
Posts: 137
Re: Two table specific join

Code:
SELECT a_id FROM table_X
JOIN table_Y USING(b_id)
GROUP BY a_id HAVING SUM(system_flag)=0;
Reply With Quote
  #3 (permalink)  
Old 02-28-04, 11:48
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
aus, that's pretty cool

it also works with LEFT OUTER JOIN, in case there's a row in table_X which has no rows in table_Z -- since SUM() ignores nulls, it will work too!

neat, eh?
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #4 (permalink)  
Old 02-28-04, 23:11
aus aus is offline
Registered User
 
Join Date: Oct 2003
Location: Denver, Colorado
Posts: 137
Good point, I do tend to forget about some records not showing up in the result set. I guess that if the tables were created without referential integrity enforced, the LEFT JOIN would be required.
Reply With Quote
  #5 (permalink)  
Old 03-11-04, 09:54
andris2000 andris2000 is offline
Registered User
 
Join Date: Feb 2004
Posts: 4
SELECT a_id FROM table_X
JOIN table_Y USING(b_id)
GROUP BY a_id HAVING SUM(system_flag)=0;

Bingo!

Thank you very much
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