Let’s say I have this table. Let’s say it looks something like this:
table values (
- id (int, primary key, auto increment)
- object_id (foreign key on a
different table. Used to search for specific object values)
- year
(varchar, because in someone's infinite wisdom using "1981-1982" in
addition to 1981 and 1982 values is a good idea)
- high_price
- low_price
)
Now, this would be an easy thing to do if the data was simply added at the end with updated prices. However, the data is not nice looking. For instance, let’s look at a three-year range:
(id, object_id, year, high_price, low_price)
- 259, 60, 1976, 34000, 29000
- 260, 60, 1977, 35000, 31000
- 261, 60, 1978, 36000, 35000
- 1103, 60, 1976, 29000, 25000
- 1104, 60, 1977, 36000, 32000
- 1105, 60, 1978, 38000, 33000
- 2634, 60, 1976, 34000, 30000
- 2635, 60, 1977, 37000, 33000
- 2636, 60, 1978, 40000, 35000
If I wanted to grab the 18 most recent entries for a particular year, how would I go about doing this? It also needs to be in reverse order, so that when I chart it the most recent year is on the right. I won’t necessarily know the most recent year, and it may not be the current year (most likely won’t be the current year).
I have a SQL statement in my php that looks like this:
$sql = "SELECT * FROM `values` WHERE `object_id`='$id'
ORDER BY `year` DESC, `id` DESC LIMIT 18"
$result = $mysqli->query($sql);
This seems to get the right values, but puts them in the wrong order. I can simply go through the list in a reverse loop, but I’d like to know if there is a SQL statement that can do this for me.
Thanks!
Edit: I have tried the SQL with ORDER BY year ASC, id DESC and ORDER BY year DESC, id ASC. Neither of these work. The first still spits them out backwards, while the second spits them out from the first year instead of the last.
Add an outer select and flip the order on year: