the way i have it is that I set up an insert command which works well
it add the entry to my DB ...since i want to insert other entries in other tables using the unique index that was obtained from the first insertion I do a query obtain the index then reuse it other insert...
though this works fine...I am sure there has to be a better way
any suggestions?
thank you :)
for the autoincrement index you can use
SELECT LAST_INSERT_ID()
or mysql_insert_id() in PHP if you happen to use this language
Related
When adding a row to a table, but first checking to see if it exists first Which would be the most efficient way of handling this?
Would it be a case of query to see if it exist, if not then insert.
Or using on duplicate?
Or simply replace (Would this work, if the row did not exist)?
Thanks
I think this is the fastest way in MySQL:
REPLACE into table (col1, col2) values(1, 'ABC')
EDIT:
MySQL will delete the row if it does exist and insert a new one.
I think you need INSERT IGNORE see this or INSERT ON DUPLICATE KEY UPDATE
depends what you mean by 'exists' if there is a unique field you can check against such as 'email' or 'login' then you can just try the insert and mysql raise error if exists, otherwise you'd do the replace as juergen d just suggested.
NB: don't use replace if you wanted your timestamps for any reason (such as if they're used in encrypted passwords or salt
If a column is made unique in a database table structure, is there any need to do a check to see if a new value to be inserted already exists in the table via script? Or would it be fine just to insert values letting the DBMS filter non-new values?
When you will try to insert a duplicate value in a unique column, your insert query will fail. So it might be a good idea to make sure you are checking to see if your insert queries went well or not. Althought regardless of the situation you should always check if your insert query went through or not :)
You should always validate your data before inserting it on the database. That being said, what will happen if you try to insert a non-unique value on a unique defined column is an SQLexception.
In order to validate this before insertion, you could for example do a
select 1
from mytable_with_unique_column
where my_unique_column = myNewValue
If the query returns anything, then simply do not try to insert as that will throw an SQLException.
Verification of unique constraint is definitely an overkill.
When you put unique constraint on your column, an implicit index is created for this column. Thus, DBMS can (and will) verify your data much faster. Unfortunately, when you try to insert duplicate value into your column, you will get constraint violation exception you have to deal with (but you have to deal with such error while using script verification either).
Good luck.
You can combine the insert statement and validation select into one statement:
insert into mytable_with_unique_column (...) values (...)
where not exists
(
select 1
from mytable_with_unique_column
where my_unique_column = myNewValue
)
This will only insert a new row if there isn't already a row with the given unique value.
Does anyone know if it is possible to get the auto increment id of a field in a mysql table and use it in the same insert?
e.g
assuming the new id here would be 2, an evaluated statement would look as follows
"insert into table (field1) values( 'random-2')"
I know it's possible for me to return this in the code and run another insert, but I wondered if there was a quicker way to 'compute' this during the insert?
1 thought I had was "insert into table (field1) values( 'random' + (select max(id) FROM table) + 1)"
but I'm worried about possible issues with multiple inserts occurring at the same time.
Thanks
It's not possible. You're gonna have to update the entry afterwards.
I'm worried about possible issues with multiple inserts occurring at the same time
That's only part of the problem - insert ids are only suposed to be unique - not contiguous.
If you want to do it in a single call from the application then use a stored procedure to encapsulate the insert+update or use a trigger to fire an update on insert. Or use a sequence generator instead of an autoincrement.
I'm trying to create a code for a single button where it will perform either of two actions where it will add to the database if the user currently don't have the record while it will update the user's record if the user has records already. I've done it like this:
if() {
mysql_query("INSERT INTO table...");
}
else {
mysql_query("UPDATE table SET...");
}
Is it possible?
Yes, what you've written will work. If you have a way to know if there already exists a row or not without making an additional query just for this bit of code, then do exactly as you wrote.
If, however, you planned to first SELECT from the table to see if a row exists, then conditionally INSERT or UPDATE, you will perform more queries than necessary.
It would be better to either:
Have a PRIMARY KEY or other constraint on the table prevent duplicate INSERTs. Then issue an INSERT ... ON DUPLICATE KEY UPDATE query. This will attempt to INSERT the row, and if it is a duplicate, automatically perform the specified UPDATE to that row instead.
Issue the UPDATE query and check mysql_affected_rows to see if it updated an existing row. If not, then issue the INSERT query to create the new row.
Which one is more appropriate depends on your application.
you can use INSERT ... ON DUPLICATE KEY UPDATE Syntax like:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you have properly set unique keys, you should use REPLACE so you could remove the if.
REPLACE INTO table VALUE (...);
Pay attention that this is a MySQL extension, thus not portable to other DBs.
Yes, you could try the insert then if it fails try the update.
But you could use the MYSQL sql "REPLACE" keyword, which will insert a new record if it doesn't exist or delete the existing record and insert your new one if it does.
You could also use the INSERT ... ON DUPLICATE KEY UPDATE syntax
(explained here - Link to MYSQL ref which seems to be the closest fit to your requirement.
yes it is possible
first write a query for check that record is already exist or not.
Yes it is possible , it will work
I have two INSERT commands, that are useless to me like that because the two sets of rows - the ones that are already in the table, and the ones I have as INSERT commands - are not disjunct. Both commands insert lots of rows, and lots of values.
Therefore I get the duplicate entry error if I want to execute those lines.
Is there any easy way to 'convert' those commands into UPDATE?
I know this sounds stupid, because why do I make INSERT commands, if I want to UPDATE. Just to make it a clear scenario: another developer gave me the script:)
Thanks in advance,
Daniel
EDIT - problem solved
First I created a table and filled it up with my INSERT commands, then I used the following REPLACE command:
REPLACE
INTO table_1
SELECT *
FROM table_2;
This can originally be found at: How can I merge two MySQL tables?
MySQL's REPLACE keyword does this. Simply replace the INSERT keyword in your queries with the word REPLACE and it should update the rows instead of inserting new ones. Please note that it will only work if you're inserting a primary key or unique key column.
You would have to rewrite them to updates by hand. If I encouter such a problem, I query for the count of certain primary key first, if none is found I insert a generic dataset and update it afterwards. By this, new data can be added and already existing data will be updated, and you don't have to differentiate between inserting new data and updating data.
For MySQL, you can use either the INSERT IGNORE or the INSERT ... ON DUPLICATE UPDATE syntaxes. See the MySQL reference manual
You can easily modify your queries to update duplicate rows, see INSERT ... ON DUPLICATE KEY syntax in MySQL