Ask the Expert

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?


    Requires Free Membership to View

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: