Connecting Tech Pros Worldwide Help | Site Map

selection on many to many with uniqueness of one field

Newbie
 
Join Date: Aug 2008
Posts: 1
#1: Aug 22 '08
hi, first of all, sorry for my bad english!

i have 3 tables: companies, contacts and an inbetween table: compcont

i want to select some companies and i need only one contact for each company (but there are a lot more in the database)

what contact isn't important, the first one the script finds is ok for me.

how to i build this querry?
it's probably quite simple but i can't find it on the web or in my books.

the script i have so far is: (i just wrote it out of my head, probably with error's)
Expand|Select|Wrap|Line Numbers
  1. SELECT compName, street, number, city, firstName, lastName
  2. FROM companies INNER JOIN compcont ON companies.companyNr = compcont.companyNr INNER JOIN contacts ON compcont.contactNr = contacts.contactNr
But this script generates of course multiple records for one company if it has more then one contact.

i hope you understand what i mean and can help me out, i've been hurting my poor little brains over this!

thanks in advance!
greetz
Marloes
mwasif's Avatar
Moderator
 
Join Date: Jul 2006
Location: Pakistan
Posts: 718
#2: Aug 22 '08

re: selection on many to many with uniqueness of one field


Use GROUP BY
Expand|Select|Wrap|Line Numbers
  1. SELECT compName, street, number, city, firstName, lastName
  2. FROM companies INNER JOIN compcont ON companies.companyNr = compcont.companyNr INNER JOIN contacts ON compcont.contactNr = contacts.contactNr
  3. GROUP BY companies.companyNr
Reply