Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL SELECT FROM Many To Many

Status
Not open for further replies.

chrispem

Programmer
Aug 13, 2007
2
GB
Ok, I really need some help.

I have three tables: products, bundles, and bundleItems

product(id, name)
bundle(id, name)
bundleItems(productid, bundleid)

OK, What I want to do is return a list of ALL distinct bundles and if they have products associated or not.

for example:

bundleid bundlename hasproducts
1 get 1 free false
2 discount true
3 multibuy false

Any ideas welcome but I want the SQL to be efficient as there could be many records.

Thanks in advance.

Chris
 
Code:
select bundle.id
     , bundle.name
     , case when exists
        ( select 1 from bundleItems
            where bundleid = bundle.id )
            then 'true' else 'false'
         end as has products
  from bundle
Code:
select bundle.id
     , bundle.name
     , case when count(bundleid) = 0
            then 'true' else 'false'
         end as has products
  from bundle
left outer
  join bundleItems
    on bundleItems.bundleid = bundle.id
group
    by bundle.id

r937.com | rudy.ca
 
Many thanks, not seen the CASE used in SQL before. Will read up on it.

Have a great day.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top