Problem solve Get help with specific problems with your technologies, process and projects.

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 last published in December 2002

Dig Deeper on Oracle and SQL

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.

Start the conversation

Send me notifications when other members comment.

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

Please create a username to comment.