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 > DB2 > A Partial Except query?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-26-10, 07:37
rocker86 rocker86 is offline
Registered User
 
Join Date: Jul 2009
Posts: 37
A Partial Except query?

Hi,

My sample data looks like this:

Table1:

ID Name Age

2 Ted 34
4 Kim 43
5 Joe 29

Table2:

Name Age

Ted 34
Tom 23

Except clause only works for exact column numbers and type matches. The result I'm looking for is this:

4 Kim 43
5 Joe 29

Basically the minus of table 2 from table 1 for matching column name and age, but since table 2 is without an ID column, its getting tricky and I'm unable to use EXCEPT as I want the added ID information in the end result.

The only way I could think of was:

select tb1.id,tb1.name,tb1.age from
(select name,age from table1
except
select name,age from table2)
inner join table1 on
table1.name=tb1.name and table1.age=tb1.age

Now if my simple table1 gets replaced by a select statement covering 5-6 joins, my solution above has got to be the least ideal way to do this isn't it?

thanks!
Reply With Quote
  #2 (permalink)  
Old 11-26-10, 10:25
stolze stolze is offline
Registered User
 
Join Date: Jan 2007
Location: Jena, Germany
Posts: 2,662
Another option to avoid the join could be this:
Code:
SELECT *
FROM   table1
WHERE  ( name, age ) NOT IN ( SELECT name, age
                              FROM   table2 )
The subselect should usually only be executed once because it is uncorrelated. (Depends on the optimizer decision, of course.)
__________________
Knut Stolze
IBM DB2 Analytics Accelerator
IBM Germany Research & Development
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