简体   繁体   中英

MySQL historical data lookup

I've been looking around and trying to get this to work but I can't seem to get it. I have 2 tables:

TABLE: products

| id | name      | some more values |
|----|-----------|------------------|
| 1  | Product 1 | Value 1          |
| 2  | Product 2 | Value 2          |
| 3  | Product 3 | Value 3          |


TABLE: value

| pid | value     | stamp            |
|-----|-----------|------------------|
| 1   | 7         | 2015-07-11       |
| 2   | 4         | 2015-07-11       |
| 3   | 8         | 2015-07-11       |
| 1   | 9         | 2015-07-21       |
| 2   | 4         | 2015-07-21       |
| 3   | 6         | 2015-07-21       |

First table simply has a list of products, second table has a value for each product (by pid), and the timestamp the value. note: timestamps are not every day, nor are they evenly spaced.

What I would like, is a resulting table like this:

| id | name      | some more values | value now | value last month |
|----|-----------|------------------|-----------|------------------|
| 1  | Product 1 | Value 1          | 9         | 7                |
| 2  | Product 2 | Value 2          | 4         | 4                |
| 3  | Product 3 | Value 3          | 6         | 8                |

where 'value now' is the value of the newest timestamp, and the 'value last month' is the value of the timestamp closest to the newest timetamp - 30 days. Keep in mind that -30 days might not have a specific timestamp, the query will need to find the closest timestamp. (looking only up or down doesn't matter, it's an approximation.)

I have made some huge queries but I'm pretty sure there must be an easier way... Any help would be appreciated.

Assuming you get last month and year by PHP or by mysql function, here is a not checked query I hope it will work on first time:

SELECT *, v_now, v_lastmonth FROM products p 
LEFT JOIN (SELECT `value` AS v_now FROM value ORDER BY stamp DESC) AS v_now ON p.id=v_now.pid
LEFT JOIN (SELECT `value` AS v_lastmonth FROM value 
WHERE month(stamp)='$month' AND year(stamp)='$year'
ORDER BY stamp DESC) AS v_now ON p.id=v_now.pid

You can use group by to get one row for each product result.

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