Question

Given two simple tables in MySQL database.

  • product (having attributes, prod_id, prod_name ...)
  • product_image (having attributes, product_image_id, prod_id (references prod_id in the product table), prod_image ...)

The relationship between these tables in intuitive - one to many from product to product_image.


I need to retrieve a result set (only prod_image) from the product_image table having maximum product_image_id in each group of products.

The following query does exactly that.

SELECT p.prod_image
FROM   product_image p 
WHERE  p.product_image_id IN(SELECT max(pp.product_image_id) 
                             FROM   product_image pp 
                             GROUP  BY pp.prod_id) 

How can this query be rewritten using EXISTS()?

Was it helpful?

Solution

The following query follows the logic of your question, which is to get the maximum prod_image_id for each prod_id.

SELECT p1.prod_image 
FROM   product_image p1 
WHERE  NOT EXISTS(SELECT 1 
                  FROM   product_image p2 
                  WHERE  p1.prod_id = p2.prod_id 
                         AND p1.product_image_id < p2.product_image_id) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top