Maximum value in many-to-many relationships

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

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.