Q

Maximum value in many-to-many relationships

I have the tables, Widgets and Categories, and a table WidgetCategories that expresses the many-to-many relationship...

between a Widget and a Category. Each widget has a 'price' field. I want to write a query that, given a category id, returns the most expensive widget of that category. I end up wanting to do something like (pardon the pseudo-SQL):

tempTable := 
SELECT widgetID, price
FROM Widgets, WidgetCategories WHERE
Widgets.widgetID = WidgetCategories.widgetID AND
WidgetCategories.categoryID = $given_category$

where $given_category$ is the category I'm interested in, followed by

SELECT widgetID, price FROM tempTable
WHERE price = MAX(price)

My solution seems very awkward, with the creation of a temp table. Is there any way to do this better?


You're almost there. Just make your temp table query a subquery of the retrieval query:

select Widgets.widgetID
     , price
  from Widgets 
     , WidgetCategories 
 where Widgets.widgetID 
     = WidgetCategories.widgetID 
   and WidgetCategories.categoryID 
     = $given_category$
   and price 
     = ( select max(price)
           from Widgets
              , WidgetCategories 
          where Widgets.widgetID 
              = WidgetCategories.widgetID 
            and WidgetCategories.categoryID 
              = $given_category$ )

Note that both the outer query and subquery need to check for the selected category.

For More Information


This was first published in December 2002

Dig Deeper

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close