Unix Technical Forum

SEO

vBulletin Search Engine Optimization


Go Back   Unix Technical Forum > Database Server Software > Microsoft SQL Server > SQL Server

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 03-01-2008, 02:43 PM
Artie
 
Posts: n/a
Default Not Exists joining 2 tables

Hi,
I was hoping somebody could assist me with this. I need to find accounts
that do not contain a contact person called 'Accounting'. Each account may
contain multiple contacts.

Here's my query to find accounts that DO contain an 'Accounting' contact:

SELECT company.code, company.name, company.type,
contacts.fullname
FROM company INNER JOIN
contacts ON company.code = contacts.code
WHERE (company.type in ('C', 'R')) and (contacts.fullname =
'Accounting')
order by company.code


How do I find accounts that DO NOT contain an 'Accounting' contact?

Thanks






Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 03-01-2008, 02:43 PM
Erland Sommarskog
 
Posts: n/a
Default Re: Not Exists joining 2 tables

Artie (artie2269@yahoo.com) writes:
> I was hoping somebody could assist me with this. I need to find
> accounts that do not contain a contact person called 'Accounting'. Each
> account may contain multiple contacts.
>
> Here's my query to find accounts that DO contain an 'Accounting' contact:
>
> SELECT company.code, company.name, company.type,
> contacts.fullname
> FROM company INNER JOIN
> contacts ON company.code = contacts.code
> WHERE (company.type in ('C', 'R')) and (contacts.fullname =
> 'Accounting')
> order by company.code
>
>
> How do I find accounts that DO NOT contain an 'Accounting' contact?


SELECT cm.code, cm.name, cm.type, ct.fullname
FROM company cm
JOIN contacts ct ON cm.code = ct.code
WHERE cm.type in ('C', 'R'))
AND NOT EXISTS (SELECT *
FROM contacts ct2
WHERE cm.code = ct2.code
AND ct2.fullname = 'Accounting')
ORDER BY cm.code



--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 03-01-2008, 02:43 PM
Artie
 
Posts: n/a
Default Re: Not Exists joining 2 tables

Thanks Erland.


"Erland Sommarskog" <esquel@sommarskog.se> wrote in message
news:Xns99D2F052488E0Yazorman@127.0.0.1...
> Artie (artie2269@yahoo.com) writes:
>> I was hoping somebody could assist me with this. I need to find
>> accounts that do not contain a contact person called 'Accounting'. Each
>> account may contain multiple contacts.
>>
>> Here's my query to find accounts that DO contain an 'Accounting' contact:
>>
>> SELECT company.code, company.name, company.type,
>> contacts.fullname
>> FROM company INNER JOIN
>> contacts ON company.code = contacts.code
>> WHERE (company.type in ('C', 'R')) and (contacts.fullname =
>> 'Accounting')
>> order by company.code
>>
>>
>> How do I find accounts that DO NOT contain an 'Accounting' contact?

>
> SELECT cm.code, cm.name, cm.type, ct.fullname
> FROM company cm
> JOIN contacts ct ON cm.code = ct.code
> WHERE cm.type in ('C', 'R'))
> AND NOT EXISTS (SELECT *
> FROM contacts ct2
> WHERE cm.code = ct2.code
> AND ct2.fullname = 'Accounting')
> ORDER BY cm.code
>
>
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
>
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pro...ads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodinf...ons/books.mspx



Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 03-01-2008, 02:43 PM
--CELKO--
 
Posts: n/a
Default Re: Not Exists joining 2 tables

Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. If you know how, follow ISO-11179 data element naming
conventions and formatting rules. Sample data is also a good idea,
along with clear specifications. It is very hard to debug code when
you do not let us see it.

>> I need to find accounts that do not contain a contact person called 'Accounting'. Each account may contain multiple contacts.<<


What is the key of the Companies table (your singular name means that
you have one or fewer rows in that table, but I assume this is part of
the other violations of ISO-11179 with uselessly vague data element
names like "name" (of my dog?) "code" (ZIP code?) and "type" (blood
type?).

It sorta looks like code is the key, but that makes no sense. BY
DEFINITION a code of any kind cannot be a key; this is fundamental.

You need a DUNS number or other industry standard company identifier.
Your spec asked only for for the companies without a contact =
'Accounting'; but we have no idea if the Contacts table (properly
named!) has a reference to the companies.

Here is a weird way to do this, based on guessing at your DDL:

SELECT CT.company_name
FROM Contacts AS CT
GROUP BY CT.company_name
HAVING SUM(CASE WHEN CT.contact_name = 'Accounting' THEN 1 ELSE 0
END)= 0;

This is untested; if we had DDL, we could try it!! I assumed that
Contacts ought to be a relationship between a company and a lawful
person or role within the company.

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 03-01-2008, 02:43 PM
Artie
 
Posts: n/a
Default Re: Not Exists joining 2 tables

I did not post the full DDL because there are so many fields that are not
relevant and felt it would complicate things. It would open up a can of
worms as to why it is desgined the way it is (I did not design it).

Erland's response did the trick.

Do you guys (or gals) have a preferred method of generating insert
statements that pull data from the table? I have used sp_generate_inserts
from http://vyaskn.tripod.com but have run into some cases where the 8000
char limit was not enough.

I really appreciate the help all of you provide on these boards to newbs
like me.


"--CELKO--" <jcelko212@earthlink.net> wrote in message
news:1193185951.805397.62450@v23g2000prn.googlegro ups.com...
> Please post DDL, so that people do not have to guess what the keys,
> constraints, Declarative Referential Integrity, data types, etc. in
> your schema are. If you know how, follow ISO-11179 data element naming
> conventions and formatting rules. Sample data is also a good idea,
> along with clear specifications. It is very hard to debug code when
> you do not let us see it.
>
>>> I need to find accounts that do not contain a contact person called
>>> 'Accounting'. Each account may contain multiple contacts.<<

>
> What is the key of the Companies table (your singular name means that
> you have one or fewer rows in that table, but I assume this is part of
> the other violations of ISO-11179 with uselessly vague data element
> names like "name" (of my dog?) "code" (ZIP code?) and "type" (blood
> type?).
>
> It sorta looks like code is the key, but that makes no sense. BY
> DEFINITION a code of any kind cannot be a key; this is fundamental.
>
> You need a DUNS number or other industry standard company identifier.
> Your spec asked only for for the companies without a contact =
> 'Accounting'; but we have no idea if the Contacts table (properly
> named!) has a reference to the companies.
>
> Here is a weird way to do this, based on guessing at your DDL:
>
> SELECT CT.company_name
> FROM Contacts AS CT
> GROUP BY CT.company_name
> HAVING SUM(CASE WHEN CT.contact_name = 'Accounting' THEN 1 ELSE 0
> END)= 0;
>
> This is untested; if we had DDL, we could try it!! I assumed that
> Contacts ought to be a relationship between a company and a lawful
> person or role within the company.
>



Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 03-01-2008, 02:43 PM
Erland Sommarskog
 
Posts: n/a
Default Re: Not Exists joining 2 tables

Artie (artie2269@yahoo.com) writes:
> I did not post the full DDL because there are so many fields that are not
> relevant and felt it would complicate things. It would open up a can of
> worms as to why it is desgined the way it is (I did not design it).


In many cases it's better to post a simplied schema that captures the
essence of the problem.

> Do you guys (or gals) have a preferred method of generating insert
> statements that pull data from the table? I have used sp_generate_inserts
> from http://vyaskn.tripod.com but have run into some cases where the 8000
> char limit was not enough.


I haven't looked in to Vyas's code, but if you are on SQL 2005, it should
be easy to modify it to use varchar(MAX) rather than varchar(8000).

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 03-01-2008, 02:43 PM
Ed Murphy
 
Posts: n/a
Default Re: Not Exists joining 2 tables

--CELKO-- wrote:

> Your spec asked only for for the companies without a contact =
> 'Accounting'; but we have no idea if the Contacts table (properly
> named!) has a reference to the companies.


Yes, we do. "It sorta looks like code is the key", by your own
admission, and his "companies with a contact = 'Accounting')"
sample query backs this up:

FROM company INNER JOIN
contacts ON company.code = contacts.code

Granted, "'code' is a bad name for a key column" is a valid complaint.

> SELECT CT.company_name
> FROM Contacts AS CT
> GROUP BY CT.company_name
> HAVING SUM(CASE WHEN CT.contact_name = 'Accounting' THEN 1 ELSE 0
> END)= 0;
>
> This is untested; if we had DDL, we could try it!! I assumed that
> Contacts ought to be a relationship between a company and a lawful
> person or role within the company.


You mean a many-to-many linking table between Companies and Persons
(i.e. a person might be a contact for multiple companies)? Okay, but
I still don't see why you would get company_name from any table other
than Companies. Basic normalization.

If you do get company_name from Companies, then you might have a company
with no contacts at all. You could use LEFT JOIN and COALESCE(SUM()),
but Erland's NOT EXISTS is more natural.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 03-01-2008, 02:45 PM
creedp.71@gmail.com
 
Posts: n/a
Default Re: Not Exists joining 2 tables

On 25 Oct, 21:48, Ed Murphy <emurph...@socal.rr.com> wrote:
> --CELKO-- wrote:
> > Your spec asked only for for the companies without a contact =
> > 'Accounting'; but we have no idea if the Contacts table (properly
> > named!) has a reference to the companies.

>
> Yes, we do. "It sorta looks like code is the key", by your own
> admission, and his "companies with a contact = 'Accounting')"
> sample query backs this up:
>
> FROM company INNER JOIN
> contacts ON company.code = contacts.code
>
> Granted, "'code' is a bad name for a key column" is a valid complaint.
>
> > SELECT CT.company_name
> > FROM Contacts AS CT
> > GROUP BY CT.company_name
> > HAVING SUM(CASE WHEN CT.contact_name = 'Accounting' THEN 1 ELSE 0
> > END)= 0;

>
> >
> > This is untested; if we had DDL, we could try it!! I assumed that
> > Contacts ought to be a relationship between a company and a lawful
> > person or role within the company.

>
> You mean a many-to-many linking table between Companies and Persons
> (i.e. a person might be a contact for multiple companies)? Okay, but
> I still don't see why you would get company_name from any table other
> than Companies. Basic normalization.
>
> If you do get company_name from Companies, then you might have a company
> with no contacts at all. You could use LEFT JOIN and COALESCE(SUM()),
> but Erland's NOT EXISTS is more natural.


I know this thread is month old but I couldn't help but renew it. It
warms my heart to see a couple people that know how to use an NOT
EXISTS clause with a correlated subquery properly, especially when so
many people don't understand the impact of the seemingly simple "NOT
IN()" version which would use a nested sub-select instead leaving an
exponentialy larger footprint on the DB.
However, unless I am mistaken, this is a classic case of exactly the
type of scenario that forced me to switch from the old-school Oracle
SQL+ syntax (pre v8) and start using the ANSI SQL syntax that seems
far too "wordy" just to join a couple tables together. It was a
scenario just like this that I realized you could only do with the
newer syntax. And (depending on the data of course) it may be a more
efficient query than the correlated subquery.

The basic idea is just change the join to an outer join, and then move
the additional criteria into the JOIN clause just like it's another
column you're joining to. Then the only criteria in the where clause
will be a test for NULL in the primary key column of the joining table
which would mean there's not a matching record to the join. This
gives you the ability to evaluate criteria on the records both before
and after the join is made. This is also a common method used in ETL
when writing an "insert into select from" statement in a single
statement that will give you a single DML statement that both tests
for the existence of a record in a table before attempting to insert a
batch of rows into it.

Consider this alternative and let me know if I screw this one up,
after all, it's getting late, and I'm still at work .....

SELECT company.code, company.name, company.type,
contacts.fullname
FROM company Left JOIN
contacts ON company.code = contacts.code
AND (company.type in ('C', 'R')) and (contacts.fullname =
'Accounting')
WHERE contacts.code IS NULL
order by company.code
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 03-01-2008, 02:45 PM
Ed Murphy
 
Posts: n/a
Default Re: Not Exists joining 2 tables

creedp.71@gmail.com wrote:

> Consider this alternative and let me know if I screw this one up,
> after all, it's getting late, and I'm still at work .....
>
> SELECT company.code, company.name, company.type,
> contacts.fullname
> FROM company Left JOIN
> contacts ON company.code = contacts.code
> AND (company.type in ('C', 'R')) and (contacts.fullname =
> 'Accounting')
> WHERE contacts.code IS NULL
> order by company.code


I think this would work (except in the unlikely case that
contacts.code is nullable, in which case it might return
some data that it shouldn't). But NOT EXISTS has the strong
advantage of letting you say what you mean.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 03-01-2008, 02:45 PM
jhofmeyr@googlemail.com
 
Posts: n/a
Default Re: Not Exists joining 2 tables

On Nov 28, 5:46 am, Ed Murphy <emurph...@socal.rr.com> wrote:
> creedp...@gmail.com wrote:
> > Consider this alternative and let me know if I screw this one up,
> > after all, it's getting late, and I'm still at work .....

>
> > SELECT company.code, company.name, company.type,
> > contacts.fullname
> > FROM company Left JOIN
> > contacts ON company.code = contacts.code
> > AND (company.type in ('C', 'R')) and (contacts.fullname =
> > 'Accounting')
> > WHERE contacts.code IS NULL
> > order by company.code

>
> I think this would work (except in the unlikely case that
> contacts.code is nullable, in which case it might return
> some data that it shouldn't). But NOT EXISTS has the strong
> advantage of letting you say what you mean.


The last time I tried this (on a fairly complex query as well) on SQL
2005, the execution plan of using a NOT EXISTS and LEFT OUTER JOIN to
filter rows was identical. Could it be that the query optimiser
actually understands what we are trying to achieve and derives the
best method to do so regardless of syntax these days? More likely it
was simply a quirk of the query / tables / indexing I guess...

J
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
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

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT. The time now is 03:34 AM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0
UnixAdminTalk.com

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571