Skip to content
Advertisement

MySQL selecting rows that are not in grouping

I have the following MySQL table of sample data:

I am looking for a query to select any store_id that a company would not use to purchase product. For example in prices, store_id 2 would not be used because item 2 can be bought for cheaper from store_id 1.

How would I go about this? Thank you.

Advertisement

Answer

With this query:

you get the minimum price for each item.
If you left join the table prices to the above query and keep only the non matching rows (meaning rows that don’t have the cheapest price for that item), you will get all the stores and items that can be found cheaper:

See the demo.
Results:

If you want only the stores that you would not buy anything from:

See the demo.
Results:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement