MySQL, inserting row if not exists [duplicate] - mysql

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to use if not exists while inserting a row mysql
I have problem:
I have table named "table" with 4 columns: id(int, PK, AI, Unique), col1(varchar), col2(varchar), col3(datetime)
Many users can connect to mysql server and insert rows into "table". The problem is that col2 and col3 can't exists in other row in "table".
I would write something like that:
IF NOT EXISTS (select * from table where col2='2' and col3='2012-12-12 12:12:12') INSERT INTO table(col1, col2, col3) values(1,2,'2012-12-12 12:12:12')
I assume you know what I'm trying to do.
I'm trying to do this in one statement (to avoid situation in which 2 users inserts the same row at the same time) or in transaction. If I should do it in transaction, then what type of isolation should it be? Serializable isolation causes lock tables so it can slow down inserting process much more.
Help me, please.

If you don't want duplicates for the pair of col2 and col3 (i.e. col 2 can have duplicates but any pair of col2 and col3 only appears once) you can specify this:
UNIQUE(col2,col3)
Any query which now attempts to insert a col2,col3 pair will fail. You can deal with this either using:
INSERT IGNORE INTO table(col1, col2, col3) values(1,2,'2012-12-12 12:12:12');
or if the insert should change the values you can use:
INSERT INTO table(col1, col2, col3) values(1,2,'2012-12-12 12:12:12')
ON DUPLICATE KEY UPDATE someCol=someVal

Related

Delete row before insert a new one [duplicate]

This question already has an answer here:
INSERT deleted values into a table before DELETE with a DELETE TRIGGER
(1 answer)
Closed 6 years ago.
How can I achieve to Delete a row before Insert a new one in the same Table. I tried it with a Trigger but I read that it is not possible because it could cause a deadlock.
I also wanted to save the row which should be deleted to another table (example Table B) before delete it and then Insert a new one (into Table A).
Is there any other ways to do it ?
PS: They will have the same key
You could use UPDATE...
UPDATE tbl
SET col1 = newCol1,
col2 = newCol2
WHERE etc = etc
And If you want to insert updated row to another table you could use TRIGGER AFTER UPDATE for that.
CREATE TRIGGER TriggerName ON Tbl
AFTER UPDATE
AS
INSERT INTO Log (Col1, Col2)
SELECT Col1, Col2
FROM deleted

Select Insert Query by mentioning all columns across databases

I am working on redesigning of a legacy db and I have set new names to columns of old db. So, for instance, if olddb.oldtable under dbold has column descr, I have set it as description in new newdb.netable for column.
How can I mention individual columns in my query?
I am using MYSQL
Update: Both Databases are on different IP Addresses and I am using Navicat to transfer data.
You can try like this:
INSERT INTO newtable (col1, col2, ..., )
SELECT col1, col2, ..., FROM oldtable
By trying the above query you can insert the specific column. So for example if your newtable has a column as description and old table as descr then you can mention it like:
INSERT INTO newtable (col1, col2, `description`, ..., )
SELECT col1, col2, `descr` ,..., FROM oldtable
Also if the table column list is large and you want to copy all the columns and its data then you can simply use the wildcard charater * as:
INSERT INTO newtable
SELECT * FROM oldtable;
You can insert all columns at once without the need to mention the names using this:
INSERT INTO newtable (SELECT * FROM oldtable);
It will make an 1x1 match independently of column names.
If types don't match then will insert default values (not checked for all the type combination).
Note that column number must be the same on both tables otherwise an error like this will occur:
#1136 - Column count doesn't match value count at row 1

Use auto_increment value in INSERT

What actually I am trying to do is, insert a row with INSERT INTO table (col2, col3, <...>) VALUES (col1, $something, <...>).
col1 is an auto_increment id column, and basically I want to copy that value to col2 on INSERT statement, within one query. Is this possible?
If I have understood correct then in the same INSERT statement you are trying to insert the generated AUTO_INCREMENT ID to another column.
Well, that's not possible IMO; cause if you do so the AUTO_INCREMENT ID is still not generated.
One solution is to use a stored procedure and perform the INSERT+UPDATE together like below (a sample)
create procedure usp_dowork(parameter list ...)
as
begin
INSERT INTO table (col2, col3, <...>) VALUES (NULL, $something, <...>);
update table set col2 = LAST_INSERT_ID()
where col1 = LAST_INSERT_ID();
end
You should consider using a transaction block around the DML's to make sure both the operations happens successfully.

Can you duplicate a row without knowing the schema in MySQL? [duplicate]

This question already has answers here:
In MySQL, can I copy one row to insert into the same table?
(26 answers)
Closed 7 years ago.
A great way to duplicate a row in MySQL is to use INSERT INTO ... SELECT FROM syntax.
For example:
INSERT INTO tblExample (col1, col2, col3)
SELECT col1, col2, col3 FROM tblExample WHERE pkey = 1234;
This is easy and straightforward, but from a code maintenance standpoint this is one more statement to keep track of if there are any schema changes. Suppose I add an additional column to the tblExample table, col4; now I have to remember to go back and update this SQL statement in my code. If I fail to do so, then I've just introduced a bug.
With this in mind, is there an easy to way to copy the whole row, whatever the schema may be, except for the primary key?
Very much against best practices you can do the following:
INSERT INTO myTable
SELECT * FROM myTable WHERE thisField = "abcd"
A somewhat inelegant way:
CREATE TEMPORARY TABLE tmpTable ENGINE=MEMORY SELECT * FROM realTable WHERE pk = 'something';
UPDATE tmpTable SET pk = 'something else' ;
INSERT INTO realTable SELECT * FROM tmpTable;

Duplicating all SQL rows and simultaneously changing the data

I would like to duplicate every row in my table, but in the duplicate row the value of one column will need to overwrite an existing value in another column (an intermediary step in normalising my tables).
So what I need is something like
INSERT INTO `performers` SELECT * FROM `performers`
SET `performers`.`piano` = `performers`.`singing`
As I'm no good at SQL the above, as expected, didn't work. Any ideas?
If only the duplicate row needs to have this values changed, then you can modify your INSERT:
INSERT INTO `performers`(col1, col2, col3, piano, singing)
SELECT col1, col2, col3, singing, singing
FROM `performers`
From your question I think you want to duplicate the row and then copy content of singing column into piano column?
INSERT INTO performers (row1, row2, row3, piano)
SELECT row1, row2, row3, singing
FROM performers