Is there some equivalent to PHP mysql_insert_id to fetch the last inserted UUID() primary key? (I always get 0. It works for auto_inc integers though)
No, last_insert_id() only retrieves that last generated auto_increment fields. You'll have to do a select uuid() first, then do an insert using that uuid.
However, note that uuids can't be guaranteed to be unique - they're simply very unlikely to collide. If you do require uniqueness, then go with an auto_increment - they'll never be re-used within any single table.
I found this quite short and simple solution:
set #id=UUID();
insert into <table>(<col1>,<col2>) values (#id,'another value');
select #id;
Related
I want to write a function that returns the value of a column (in this case, an auto-incrementing primary key) for a row that it inserts.
Essentially, I want to insert some new data, have a new primary key generated, then get that key. I could simply look for the highest primary key in the table, but it is possible that someone else could be running the function as well, and I could return the wrong key, right?
What's the simplest way to negotiate this problem?
As pointed in the comments, from MySQL documentation:
mysql> SELECT LAST_INSERT_ID();
-> 195
This LAST_INSERT_ID() function is not subject to a race condition like SELECT MAX(id) might be, because it's maintained within MySQL specific to your connection. It returns the ID generated for your last insert, not anybody's last insert.
How does lastInsertId() work for tables that do not have an auto-incremented field? What about tables where the primary key is made up of 2 fields?
(I'm working with MySQL)
In both cases above it will return 0.
When using an auto_increment column, it will return the last INSERT ID even if it was specified (i.e. the auto increment was not used).
That is to say you should only use lastInsertId when using auto increment. It doesn't really make sense to use it otherwise since you would have to know the keys ahead of time anyway..
I don't think it does as it is a function specifically designed to be used to retrieve the value of an AUTO_INCREMENT field.
http://php.net/manual/en/function.mysql-insert-id.php
mysql_insert_id
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
This type of thing is easy enough to test - have you tried it to see what happens?
I have a table in MySQL that for compatibility issues we assigned specific Primary Keys, therefore they can not be auto incremented.
Every time we insert a new topple (in PHP) we need to get back the latest ID inserted. It might sound stupid. but we do not generate the ID from PHP, it comes from an generic AJAX function, therefore we don't know the name of the variable containing the Primary Key, it always changes.
Is there a way, using PHP or MYSQL, to obtain the latest ID inserted for a primary key that does not auto-increment?
Unfortunately mysql_insert_id() and last_insert_id() do not work without auto_increment.
Thanks!
Head down to the comments section on this page.
http://php.net/manual/en/function.mysql-insert-id.php
And you should see some methods that might work for you.
I would try inserting the specific time_stamp and then calling that time_stamp insert again.
Dave does a good job of explaining it in this comment. Quoting him..
There is a lot of incorrect info here on "don't use AI" and "using max
is equivalent". Then you have people improperly advising you to use
psuedo-random numbers
If you're really worried about the AI field not returning because of
the inherent race conditions, just do a select statement based on the
vars you just input. If your vars are not unique, DON'T use these
psuedo-random numbers. When you have enough iterations, the
probability that the one of these randoms becomes a duplicate gets
pretty high.
Instead, just use the unix timestamp. However, don't use
UNIX_TIMESTAMP() in your query, because if you do, when you run your
select statement right after, there's a possibility that you'll end up
with a different timestamp.
Since date() continues to count up during the execution of the script,
simply store date(U) into a variable or definition. Then insert and
select based on that. Assuming you're not using mysql procedures:
<?php
define(UNIX_TIMESTAMP, date('U'));
$db->query("insert into table values('', 'a', 'b', 'c', 'd', '".UNIX_TIMESTAMP."'");
$res = $db->query("select id from table where a_col = 'a' and b_col = 'b' and c_col = 'c' and d_col = 'd' and temp_id = 'UNIX_TIMESTAMP'");
//...
?>
Following SQL statement will get last inserted id of PK.
Do it after your insert statement...
SELECT LAST_INSERT_ID() FROM tblName;
True, I forgot that you mentioned that your PK is not auto incremented. Then see the answer with timestamp solution. It's the only way I know that you can do this. But it is preferable to have auto increment field. Maybe you need to review your database scheme.
Right now, I have my database setup so that I insert a new row. But if the row I'm trying to insert is a duplicate (based off of my primary key id), then I increment the count field by 1.
Right now I want to know when I was able to create a new row instead of having it increment count. How would I do this in an efficient/proper manner?
The current method I'm thinking of doing this, is by querying the id first and checking if it exists. But I feel like there's a faster/better way. I've also read about triggers but I've heard that they're bad/risky to use.
Use INSERT ... ON DUPLICATE KEY UPDATE...
Then query for affected_rows (as #Tarek Fadel suggested). MySQL will return 1 if the row was inserted, or 2 if existing row were updated.
Use your database AUTO INCREMENT option for your primary ID field. Only propper solution.
Here you have mysql reference, but that exist in just every database engine:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
How about an auto_increment on the id column?
Otherwise you might use SELECT MAX(id) FROM TABLE to retreive the highest id and add one to it, but that isn't thread-safe since another user might execute the same insert at the same time. Auto_increment fixes that for you.
PHP's mysql_affected_rows()
I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete a row, that row's key won't ever be reused.
A preliminary search has turned up the AUTOINCREMENT keyword in mySQL. However, I'd still like to know if that will work for what I want and what the common solution to this issue is.
In MySQL that's the standard solution.
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
Unless you have an overriding reason to generate your own PK then using the autoincrement would be good enough. That way the database manages the keys. When you are inserting a row you have to leave out the primary key column.
Say you have a table table = (a, b, c) where a is the primary key then the insert statement would be
insert into table (b, c) values ('bbb', 'ccc')
and the primary key will be auto inserted by the databse.
AUTOINCREMENT is what you want. As long as you don't change the table's settings, AUTOINCREMENT will continue to grow.
AUTOINCREMENT is the standard way to automatically create a unique key. It will start at 1 (or 0, I can't remember and it doesn't matter) then increment with each new record added to the table. If a record is deleted, its key will not be reused.
Auto increment primary keys are relatively standard depending on which DBA you're talking to which week.
I believe the basic identity integer will hit about 2 billion rows(is this right for mySQL?) before running out of room so you don't have to worry about hitting the cap.
AUTO_INCREMENT is the common choice, it sets a number starting from 1 to every new row you insert. All the work of figuring out which number to use is done by the db, you just ask it back after inserting if you need to ( in php you get it by callin mysql_last_insertid I think )
For something simple auto increment is best. For something more complicated that will ultimately have a lot of entries I generate a GUID and insert that as the key.