I need help to write a MySQL query that would do the following for me:
It would select the last row from a certain column. Let's say the table name is 'mysite_codes' and the column name is 'code', there are many rows in this column, but I want the query to take the last added one and get my back one result in PHP (LIMIT 1 thing).
Would anyone please help me with this?
MySQL tables have no inherent sorting. If you want "the last added one" then you'll need an AUTO_INCREMENTing column like id.
Then you can write.
SELECT `code` FROM `mysite_codes` ORDER BY `id` DESC LIMIT 1
to get just the row with the highest id value.
Try this:
select code
from mysite_codes
order by add_date desc
limit 1
Assuming you have an auto-incremementing id column called something like "auto_id_column":
SELECT code FROM mysite_codes ORDER BY auto_id_column DESC LIMIT 0, 1;
Related
I have question, I want to insert new row to db (mysql) using php and I need to add it to first place in table, but it comes to last position.
I need to short it like this:
3
2
1
but it shorts like
1
2
3
Can you help me please?
Thanks a lot, Stepan
Assuming that you are using an incremental ID as the unique key, you can do:
order by id desc
if not, you can add a column to the DB called "created" which would be a datetime that you set to NOW() when you create the row. Then you would do:
order by created desc
SQL databases do not guarantee an order, unless you specify an ORDER BY clause.
If you have an identifier column, then you can do:
SELECT ...
FROM your_table
ORDER BY id DESC
Whenever a query like
"select * from table where userid=xx" is done, the mysql fetches these values from
first row to last row of table.
But I want to select from last to first so that recently updated values are displayed first in the results.
I cannot do "select * from table where userid=xx order by time DESC" because there is no time column in table.
I just want recently updated items in the table displayed first.
$result= mysql_query("SELECT
(SELECT column FROM table WHERE [condition] ORDER BY column LIMIT 1) as 'first',
(SELECT column FROM table WHERE [condition] ORDER BY column DESC LIMIT 1) as 'last'");
$row=mysql_fetch_array($result);
echo $row['first'];
echo $row['last'];
If you have any auto-incrementing field you could sort by that desc.
You must provide a column to order by in order to guarantee results. So you will have to either change your table structure or make a decision on what to order by.
A hack would be to pull in the data in the order presented into an array, then start popping off the bottom of that array.
You either have to have a timestamp, or autoincrement id, or some other column that you want to sort by.
Just because you get rows in a certain order from a database when not using an ORDER BY clause, does not mean that they are guaranteed to be returned in that order. It also doesn't imply any order in the result set. You need a definitive field that you can use to ORDER BY, or you cannot do what you are wanting to do.
Some hack you can do for that if you don't have columns you can rely on:
SELECT * FROM (SELECT *,(#x:=#x+1) default_ordering FROM `table_name`, (SELECT #x:=0) t2) any_name ORDER BY default_ordering DESC
I need to get next id from table (auto_increment).
I could just use SELECT * from table ORDER BY id DESC LIMIT 1;
For example I get 50. But if we delete from table two items I will get 48 but correct one
will be 51. How get correct value even we something delete from table ?
You can only use SHOW TABLE STATUS LIKE 'tablename' to fetch the auto_increment value. A simpler solution might be: SELECT MAX(id) + 1 FROM table, but this is buggy if the last entry was deleted.
show table status like 'table_name'
next id value is in 'Auto_increment' field
SHOW TABLE STATUS LIKE 'table'
The value you want is in the Auto_increment field.
Be careful about concurrency though: by the time you get around to using this value, some other client could have inserted into the table and thus your value is out of date. It's usually best to try to not need this.
SELECT LAST_INSERT_ID() + 1;
gets the last ID used in an insert in an autoincrement column + 1
I see two solutions for the next ID:
1) Select bigger value of a column with max function. Example: select max( id ) from table;
2) Using the command SHOW STATUS LIKE and get the correct index of array. Take a look: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html
Seems to me you're creating a race condition here.
Why exactly can you not insert the row you want to insert and then use LAST_INSERT_ID() to find it's ID?
What SQL query would I use to display the newest entry?
Details:
id is the primary field. I have other fields but that are not related to when they were added.
ORDER BY SomeColumn DESC
LIMIT 1
or
use the MAX() function
Since you didn't give any details about your table it is hard to answer
SELECT * from yourTable ORDER BY `id` DESC LIMIT 1;
Another (better) way would be to have a "date_added" column (date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP) so you could order by that column descending instead. Dates are more reliable than ID-assignment.
not sure if this is what your looking for but I use mysql_insert_id() after inserting a new row
The auto incremented ID columns are not always the latest records inserted, I've remember really painful experience with this behavior. Conditions where specific, it was mysql 4.1.x at the time and there was almost 1 million records, where 1 out of 3 deleted everiday, and others re inserted in the next 24hours. It made a huge mess when I realize ordering them via ID was not ordering them by age....
Since then, I use a specific column for doing age related sorts, and populating these fields with date = NOW() at each row insert.
Of course it will work to found the latest record as you want, doing an ORDER BY date DESC LIMIT 0,1on your query
SELECT Primary_Key_Field FROM table ORDER BY Primary_Key_Field DESC LIMIT 1
Replace Primary_Key_Field and table obviously :)
How would i get the last 20 results submitted in a mysql db row.
I need the 20 most recent user submitted results.
Cheers.
If you don't have timestamp or autoincrement field on that table then you can't.
Otherwise : select * from table order by id desc limit 0,20
If you are using an auto_increment primary key, its as simple as:
SELECT * FROM that_table
ORDER BY auto_increment_primary_key DESC
LIMIT 0, 20
See the Query below, there is an function available in mysql syntax below
SELECT FROM ORDER BY DESC LIMIT 0,20