简体   繁体   中英

Query MySQL for current and day old data, compute change

I am building an application that I can most easily describe as a Stock Market data tracking app (it's not exactly that).

I have a table called 'market_cache'. Every 10 minutes, a script loads that table with the most recent market data, making a new row for each stock symbol (and leaves a timestamp, of course). I'm tracking 114 stock symbols, therefore, each time this script is executed, 114 new rows are added (with a timestamps within a second or two of each other).

I'm aiming to build a table that lists all of these stocks with their current data and a 24-hour % change, so in oder to compute the change, I need a second query that pulls the same data, but from 1 day ago.

Here are the queries I'm using:

For the most recent set of data:

 SELECT DISTINCT(sym), trade_to, name, marketid, lasttrade, volume, cachetime FROM market_cache WHERE cachetime >= NOW() - INTERVAL 10 MINUTE ORDER BY name ASC LIMIT 114

I'm using the DISTINCT(sym) call to make sure that the same stock symbol isn't pulled up twice in the same query, and setting the time interval to ensure I only get the rows that have been written in the last 10 minutes. This query appears to work exactly as I want it to.

My second query, to pull the change data, looks like this:

 SELECT DISTINCT(sym), trade_to, name, marketid, lasttrade, volume, cachetime FROM market_cache WHERE cachetime >= NOW() - INTERVAL 1450 MINUTE ORDER BY name ASC LIMIT 114

This query is almost identical to the one above, except the interval, 1450 minutes (10 day + 10 minutes), is different. This query, however, does not work, and it only produces the first stock symbol (1 result).

If I try to pull data for just ONE stock symbol and get day-old data for that symbol to compute the % change, I can do that no problem. However, I'm running into trouble trying to query for all 114 stocks at once, and then another set of the same 114 stocks from a day ago.

Please help! Thanks!

You have a typo in your query:

in your first query you write

WHERE cache time >= NOW()

and then in your second query it's

WHERE cachetime >= NOW()

Isn't your 'where' clause wrong?

Don't you want something like this:

WHERE cachetime >= NOW() - INTERVAL 1450 MINUTE
      and cachetime <= NOW() - INTERVAL 1440 MINUTE

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