Discover last insert ID of autoincrement column in MySQL - php

I'm currently using:
SELECT MAX(id) FROM table
To discover the current id of a certain table, but i heard this can bring bad results. What is the proper way of doing that? Please, notice that i'm not INSERTING or DELETING anything before that query. I just want to know the current ID, without prior INSERT or DELETE.

Perform the following SQL:
SHOW TABLE STATUS LIKE 'TABLENAME'
Then check field AUTO_INCREMENT

You can use the following query:
SELECT id FROM table ORDER BY id DESC LIMIT 1;

Related

INSERT INTO table SELECT not giving correct last_id

I have 2 tables with similar columns in MYSQL. I am copying data from one to another with INSERT INTO table2 SELECT * FROM table1 WHERE column1=smth. I have different columns as autoincrement and KEY in tables. When I use mysqli_insert_id i get the first one rather then last one inserted. Is there any way to get the last one?
Thanks
There is no inherit ordering of data in a relational database. You have to specify which field it is that you wish to order by like:
INSERT INTO table2
SELECT *
FROM table1
WHERE column1=smth
ORDER BY <field to sort by here>
LIMIT 1;
Relying on the order a record is written to a table is a very bad idea. If you have an auto-numbered id on table1 then just use ORDER BY id DESC LIMIT 1 to sort the result set by ID in descending order and pick the last one.
Updated to address OP's question about mysqli_insert_id
According to the Mysql reference the function called here is last_insert_id() where it states:
Important If you insert multiple rows using a single INSERT statement,
LAST_INSERT_ID() returns the value generated for the first inserted
row only. The reason for this is to make it possible to reproduce
easily the same INSERT statement against some other server.
Unfortunately, you'll have to do a second query to get the true "Last inserted id". Your best bet might be to run a SELECT COUNT(*) FROM table1 WHERE column1=smth; and then use that count(*) return to add to the mysqli_insert_id value. That's not great, but if you have high volume where this one function is getting hit a lot, this is probably the safest route.
The less safe route would be SELECT max(id) FROM table2 or SELECT max(id) FROM table2 Where column1=smth. But... again, depending on your keys and the number of times this insert is getting hit, this might be risky.

Auto remove old records from SQL table on insert request

I'm looking for a solution to auto-remove the oldest record of a table when a new record is inserted :
I want maximum 3 different records with different data but same userID, and I would like to make my table automatically remove the oldest record when a new one is inserted.
I think it's clear enough to be understood.. If not, I'll try to explain.
Sorry for bad english, not my main language
Thanks
Could you try this kind of request ?
delete
from table_name
where id not in (
select id
from table_name
order by timestamp_column desc
limit 0,3
)

How get incremented value from table

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?

How to get latest ID number in a table?

How can I get the latest ID in a table?
If you mean the latest generated ID from an insert statement with an auto-increment column, then mysql_insert_id() should help ya out
SELECT max(id) FROM table
SELECT id FROM table ORDER BY id DESC LIMIT 1 should work as well
IF you've just inserted into a table with auto_increment you can run right after your query.
SELECT last_insert_id();
Otherwise the max(id) FROM table
If the table has an auto_increment column defined - you can check by looking for "auto_increment" in the output from DESC your_table, use:
mysql_insert_id
Otherwise, you have these options:
SELECT MAX(id) FROM your_table
SELECT id FROM your_table ORDER BY id LIMIT 1
If there are no inserts being done on a table, then SELECT MAX(ID) should be fine. However, every database has a built-in function to return the most recently created primary key of a table after an insert has been performed. If that's what you're after, don't use MAX().
http://www.iknowkungfoo.com/blog/index.cfm/2008/6/1/Please-stop-using-SELECT-MAX-id
Also, for the id of the last record inserted, if you're using MySQLi, it would look like this:
$mysqli->insert_id
http://php.net/manual/en/mysqli.insert-id.php

PHP/Mysql Columns imageid, catid, imagedate, userid

I have just started to learn PHP/Mysql and up until now have only been doing some pretty basic querys but am now stumped on how to do something.
Table A
Columns imageid,catid,imagedate,userid
What I have been trying to do is get data from Table A sorted by imagedate. I would only like to return 1 result (imageid,userid) for each catid. Is there a way to check for uniqueness in the mysql query?
Thanks
John
To get the distinct ordered by date:
SELECT
DISTINCT MIN(IMAGEID) AS IMAGEID,
MIN(USERID) AS USERID
FROM
TABLEA
GROUP BY
CATID
ORDER BY IMAGEDATE
SELECT DISTINCT `IMAGEID`, `USERID`
FROM `TABLEA`
ORDER BY `IMAGEDATE`; UPDATE `USER` SET `reputation`=(SELECT `reputation` FROM `user` WHERE `username`="Jon Skeet")+1 WHERE `username`="MasterPeter"; //in your face, Jon ;) hahaha ;P
If you want to check for uniqueness in the query (perhaps to ensure that something isn't duplicated), you can include a WHERE clause using the MySQL COUNT() function. E.g.,
SELECT ImageID, UserID FROM TABLEA WHERE COUNT(ImageID) < 2.
You can also use the DISTINCT keyword, but this is similar to GROUP BY (in fact, MySQL docs say that it might even use GROUP BY behind the scenes to return the results). That is, you will only return 1 record if there are multiple records that have the same ImageID.
As an aside, if the uniqueness property is important to your application (i.e. you don't want multiple records with the same value for a field, e.g. email), you can define the UNIQUE constraint on a table. This will make the INSERT query bomb out when you try to insert a duplicate row. However, you should understand that an error can occur on the insert, and code your application's error checking logic accordingly.
Lookup the word DISTINCT.
Yes you can use the DISTINCT option.
select DISTINCT imageid,userid from Table A WHERE catid = XXXX

Categories