Is there a way to make this statement into one? The basic idea is to insert a tag name if it doesnt exist and to retrieve the primary key for my next statement. title column is unique.
INSERT INTO `tag_name` (`count`, `title`)
SELECT 0, #title FROM DUAL
WHERE not exists
(SELECT * FROM `tag_name` WHERE `title` = #title LIMIT 1);
If rows affect >0 then use last_insert_rowid(), otherwise run this statement
SELECT id from FROM `tag_name` WHERE `title` = #title
--- here is a test
CREATE TABLE test (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, data int unique);
//insert into test(data) select 5;
You can use
insert into ... on duplicate update
this is insert row and when key was duplicate then update it.also u can use:
insert into on duplicate update field1=field1
this will ignore on duplicate !
you can use the MySql specific Replace syntax. Check here for more information.
Related
Is it possible to update only a single field with ON DUPLICATE KEY UPDATE in a table with multiple fields?
If I have a table with three fields; key, cats, dogs where key is the primary key is it possible to update a record on duplicate key, changing only one field, (for my example cats) without changing the value in the other non-key fields (dogs). This is without knowing what the value of dogs from outside of the database at the time of insertion (i.e. I have a variable holding cats value, but not one holding dogs value)
INSERT INTO `myTable` (`key`,`cats`) VALUES('someKey1','Manx') ON DUPLICATE KEY UPDATE `cats` = 'Manx';
At the moment when I run something like this and the key already exists in the table dogs is set to NULL even when it had a value previously.
Gordon is right, it does not work the way I described. If you see this, it is not caused by the ON DUPLICATE UPDATE statement, but something else. Here is the proof:
CREATE TABLE IF NOT EXISTS `myTable` (
`key` varchar(20) NOT NULL default '',
`cats` varchar(20) default NULL,
`dogs` varchar(20) default NULL,
PRIMARY KEY (`key`)
)
The run
INSERT INTO `myTable` (`key`, `cats`, `dogs`) VALUES
('someKey1', NULL, 'jack-russell');
Then run
INSERT INTO `myTable` (`key`,`cats`) VALUES
('someKey1','Manx') ON DUPLICATE KEY UPDATE `cats` = 'manx';
Then check the table
I think you should try to UPSERT.
Please examine this:
INSERT INTO `item` (`item_name`, items_in_stock) VALUES( 'A', 27)
ON DUPLICATE KEY UPDATE `new_items_count` = `new_items_count` + 27
MySQL UPSERT
Is it possible to update the source table with the LAST_INSERT_ID from the target table?
INSERT INTO `target` SELECT `a`, `b` FROM `source`
The target table has an auto increment key id which I would like to store in the source table for further usage.
Would save me a lot of computing power if something like this would be possible :)
Immediately after executing:
INSERT INTO `target` SELECT `a`, `b` FROM `source`
Call an update on the source table as below:
UPDATE `source`
SET field_name = LAST_INSERT_ID()
WHERE col_name_x = some_value_or_expression
Change column names and where conditions and then execute it.
In MySQL, you can insert a row and update the 'last insert ID' at the same time. I'm using this trick to be able to insert items conditionally (uniqueness) and still get the unique ID in all cases.
The code below works. The problem is that the ON DUPLICATE KEY statement also updates the Auto_increment value. Is it possible to avoid that?
CREATE TABLE T(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
X VARCHAR(64) NOT NULL UNIQUE
) ENGINE = InnoDB DEFAULT CHARSET=utf8;
INSERT INTO T(X) VALUES ('x') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();
INSERT INTO T(X) VALUES ('x') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();
Now we have one entry with id=1. However, the next entry will have id=3 since the Auto_increment value was updated when the second INSERT failed. This can be checked as follows:
SELECT Auto_increment FROM information_schema.tables WHERE table_name = 't'
AND table_schema = DATABASE();
Q: Is it possible to use this trick (or equivalent) and keep the Auto_increment value? Obviously, in this case, it doesn't need to get updated.
So I have a table like this:
create table `test` (
`testId` int(11) not null auto_increment,
`text` varchar(10) not null default '',
primary key(`testId`),
unique(`text`)
) engine=innodb;
My insert would be
insert into test (text) values ('a');
insert into test (text) values ('b');
insert into test (text) values ('a');
the 3rd insert will fail, but I want it to return the testId for the duplicate (for 'a').
Is this possible without writing a second query?
You can't do this in an INSERT query because the INSERT does not return any rows.
When an INSERT fails because of a duplicated key - normally the thing that built the query knows what data it sent, so it could use this.
You may be able to achieve what you want by using 12.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE
If a table contains an AUTO_INCREMENT
column and INSERT ... UPDATE inserts a
row, the LAST_INSERT_ID() function
returns the AUTO_INCREMENT value. If
the statement updates a row instead,
LAST_INSERT_ID() is not meaningful.
However, you can work around this by
using LAST_INSERT_ID(expr). Suppose
that id is the AUTO_INCREMENT column.
To make LAST_INSERT_ID() meaningful
for updates, insert rows as follows:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;
There are two ways of doing this. If you just want to replace the existing data, you can use
REPLACE INTO <table_name> VALUES <values>
That is the simplest thing. But if you just want to check whether the data exist, you can first, do this
SELECT COUNT(*) FROM <table> WHERE <field>='<field_value>
If exists, query returns more than 0.
Hope this helps.
as briefly explained in subject, I need to create a table by selecting existing value.
The thing I would like to achieve is to have another column with auto incremented value.
This is what I already tried:
CREATE TEMPORARY TABLE temp_tb (
`row_id` bigint(20) NOT NULL AUTO_INCREMENT,
`stm_id` bigint(20) NOT NULL,
descr varchar(20) NOT NULL,
PRIMARY KEY (row_id)
);
Then after with a select:
INSERT INTO temp_tb (
select stm_id,descr from tb_export
)
I was expecting to have the row_id column prefilled at insert time, but I just got sql syntax error telling me that column count doesn't match value count.
Do you know if this is possible to achieve ?
thanks
you should provide the names of the columns you are inserting into your temp_tb:
INSERT INTO temp_tb (stm_id, descr) (
select stm_id,descr from tb_export
)
If I am not mistaken, the syntax error has to do with your insert syntax. You have a temp_tb that has 3 fields, all not null. You are inserting 2 fields into that table with your insert statement. The MySQL ref lists the syntax for insert using select as:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;