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 > Informix > Select first match in child table for each row in parent table

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-13-11, 13:19
bartell430 bartell430 is offline
Registered User
 
Join Date: May 2011
Posts: 2
Select first match in child table for each row in parent table

Hello.

This is more a general SQL question.

I'm trying to return just the FIRST match from a child table which is correlated with a related row in a parent table. For instance:

for table parent with columns (id, name) and these values:

(1, "Bill")
(2, "Joe")

for table child with columns (parent_id, name, birth_ord)

(1, "Bob", 2)
(1, "Eve", 1)
(1, "Dan", 3)
(2, "Sue", 2)

Can I create a single sql statement (without using intermediate temp tables) that will return the first child for each parent, like this?

(id, parent name, child name)
(1, "Bill", "Eve")
(2, "Joe", "Sue")

I was hoping to use "select first 1" within a subquery but evidently this is not allowed.

Thanks,

Bill
Reply With Quote
  #2 (permalink)  
Old 05-13-11, 14:50
r937 r937 is online now
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
Code:
SELECT parent.id
     , parent.name AS parent_name
     , child.name AS child_name
  FROM parent
LEFT OUTER
  JOIN ( SELECT parent_id
              , MIN(birth_ord) AS firstborn
           FROM child
         GROUP
             BY parent_id ) AS c
    ON c.parent_id = parent.id
LEFT OUTER
  JOIN child
    ON child.parent_id = c.parent_id 
   AND child.birth_ord = c.firstborn
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 05-13-11, 16:24
bartell430 bartell430 is offline
Registered User
 
Join Date: May 2011
Posts: 2
Thanks, that all makes sense.

That gives me a starting point for my more complicated table setup. (I'm actually going from an id table to reference an addresses table to pull the hightest priority email address which could have start and end dates and where the priority code for all email codes is stored in a 3rd table)
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