Reputation: 33
I am pretty new to MySQL...so I am sure this is probably an easy fix for someone...I've tried tutorials and other help topics, but can't figure out why it isn't working.
I have a data table with an auto incrementing index. I want to select the last 2 rows of the table. This is what I have:
SELECT * FROM tburg_golf ORDER BY 'index' DESC LIMIT 2
For some reason though, it gives me the first two rows. I've tried removing the limit, changing DESC to ASC...everything I can think of.
If curious, this is part of a larger piece of code:
$result = mysql_query("SELECT * FROM tburg_golf ORDER BY 'index' DESC LIMIT 2");
while($row = mysql_fetch_assoc($result)) {
$date = $row['date'];
$day = $row['day'];
$time = $row['time'];
$icon = $row['icon'];
$forecast = $row['forecast'];
$updated = $row['updated'];
echo $date.$day.$time.$icon.$forecast.$updated.'<p>';
}
Upvotes: 2
Views: 229
Reputation: 180917
You're ordering by 'index'
which is a string constant. Column names are instead surrounded by `
Provided your auto incrementing column is actually called index
, this will work;
SELECT * FROM tburg_golf ORDER BY `index` DESC LIMIT 2
Ordering by 'index'
will sort every line by the same string, which basically will give you rows in random order.
Upvotes: 2
Reputation: 21531
Is there a field in the table called "index"?
If there is I believe the word index is a reserved word in MySQL which is why it might not work. Either rename the field or wrap it with ` instead of ' e.g.
SELECT * FROM tburg_golf ORDER BY `index` DESC LIMIT 2
Upvotes: 2
Reputation: 4042
SELECT * FROM tburg_golf ORDER BY `index` DESC LIMIT 2
If you type 'index'
MySQL will ORDER BY the string 'index'
, which is the same for all tuples, instead of your column index
.
Upvotes: 3