Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

greatest n per group - Getting most recent data if data for the day is not available with MySQL

I have a large SQL query (MySQL 5.7.32) that gets all sorts of data AND is including pricing data for a particular day, if there is price data available for this day. Done by a simple LEFT JOIN:

SELECT *
FROM merchants m CROSS JOIN products p
LEFT JOIN prices mps
    ON m.id = mps.id AND p.article_id = mps.article_id AND mps.DATE = $date

In some cases there is no price for this particular day. In that case I would like to get the last recent price available.

Is this possible with LEFT JOIN or do I have to add even more complexity to my statement?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it is possible

SELECT m.*, t.*
FROM merchants m
JOIN (
    SELECT MAX(`date`) as max_date, id
    FROM prices
    WHERE `date` <= ?
    GROUP BY id
) t ON t.id = m.id

Edit : 2 steps queries

Assuming your shop is displaying 20 products per pages. You can run a 1st query like this :

SELECT m.*
FROM merchants m
WHERE some_criterias
LIMIT 20 OFFSET 0

and then you pass the result of this 1st query to the 2nd one :

SELECT m.*, t.*
FROM merchants m
JOIN (
    SELECT MAX(`date`) as max_date, p.merchant_id
    FROM prices p
    AND merchant_id IN (?, ?, ?...)
    WHERE `date` <= ?
    GROUP BY id
) t ON t.merchant_id = m.id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...