简体   繁体   中英

Trying to use IF with MAX in MYSQL to get most recent date between 2 tables

I've got two tables (MySQL), one with a list of categories and another with a list of products which can be assigned to a category. I need to pull out the date of the most recent change across both tables so I can reset the cache for this page if needed.

I seem to be struggling with using MAX() in a CASE, currently I have this which works but the product date is just the latest one entered into the database and not necessarily the most recent.

SELECT c.pageid as caturl, p.updated as pup, c.updated as dup,

CASE WHEN p.updated > c.updated THEN p.updated ELSE c.updated END AS latest

FROM products p, categories c 

WHERE p.catid = c.id AND c.hide=0

GROUP BY c.title

When I try to use MAX() within the CASE it throws an error, as it does when using an IF.

I'd appreciate any help, thanks.

Ok, I'm taking a stab at this, two derived tables.

One, that calculate the MostRecent updated date for each category in the categories table: "catdates" (and also returns the pageid)

The Other, calculates the MostRecent updated date across all products in a given category for each category in the products table: "proddates"

Then we just join on categoryid and take the higher value.

SELECT c.pageid,
GREATEST(proddate.LastModified,catdates.LastModified) AS LastModified
from
(SELECT p.catid as catid,MAX(p.updated) AS LastModified
FROM products p
GROUP BY p.id,p.catid) proddates
INNER JOIN 
(SELECT c.id AS catid,c.pageid,MAX(c.updated) AS LastModified
FROM categories c
WHERE c.hide=0
GROUP BY c.id,c.pageid) catdates
ON proddates.catid=catdates.catid

If you only want the latest rows, something like:

SELECT   
  c.pageid as caturl
  , p.updated as pup
  , c.updated as dup
  ,GREATEST(p.updated,c.updated) AS latest
FROM products p
INNER JOIN categories c ON (p.catid = c.id)
WHERE c.hide=0
GROUP BY caturl
HAVING lastest = MAX(lastest)

The greatest function negates the need for the case when , although it does not change the query.
The real change is in the having clause that selects only the latest rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM