INSERT INTO my_table (field_1, field_2)
SELECT val_1, val_2
FROM my_table
WHERE NOT EXISTS (SELECT field_1
FROM my_table
WHERE field_2 = val_2)
LIMIT 1
I can not use unique index on field_2 field.
I'm trying to insert if not exists a tuple with field2 = val_2.
Without the "where" clause, this insert.
With the "where" clause EVEN WHEN EMPTY TABLE, it won't insert.
Any help on that?
I guess val_1 and val_2 are not columns of the table, right?
They are values that you want to insert in the table.
So drop:
FROM my_table
and use:
INSERT INTO my_table (field_1, field_2)
SELECT val_1, val_2
WHERE NOT EXISTS (
SELECT field_1
FROM my_table
WHERE field2 = val_2
)
Solution is that check if key exist:
INSERT INTO my_table (field_1, field_2) ON DUPLICATE KEY INSERT IGNORE.
this question maybe useful.
First create a unique index on the column or columns that you don't want duplicated. I cannot tell if it is on both or just field_2:
create unique index unq_my_table_field_2 on my_table(field_2);
Then ignore the error using on duplicate key update:
INSERT INTO my_table (field_1, field_2)
VALUES (val_1, val_2)
ON DUPLICATE KEY UPDATE field_2 = VALUES(val_2); -- this is a no-op, because the value is already the same
The fact the your code doesn't work on an empty table has nothing to do with the WHERE clause but with using from my_table in the from clause. If there are no rows, then the query returns . . . no rows. No surprise there that nothing gets inserted.
Related
I want to make an sql query which can insert into table1. This table references table2 with the table2_id foreign key.
my sql looks like this so far:
INSERT INTO table1 (table1_id, name, date, table2_id)
VALUES (1, "somename", "29.04.2014", (SELECT id FROM table 2 WHERE table2.name = "BOB") )
I also want to insert values into table2 if it cannot find the table2.name and then insert the key for this into table1.
Anyone knows how to do this?
I would suggest that you use insert . . . select rather than insert . . . values:
INSERT INTO hovedenhet (organisasjonsnummer, navn, stiftelsesdato, registreringsdatoEnhetsregisteret, organisasjonsform_id)
SELECT 813550202, 'SAMEIET SCHWEIGAARDSGATE 21-23', '10.01.2014', '29.04.2014', id
FROM organisasjonsformhovedenhet oh
WHERE oh.organisasjonsform = 'BOB';
Your original query will insert the row with a NULL value for the last column, if there is no match. This will not insert anything in that case.
I'm inserting some_data (a unique key column), and then using the resulting user_id (the primary key auto-increment column) in a separate statement (not shown)
INSERT IGNORE INTO users (some_data) VALUES ('test');
SELECT LAST_INSERT_ID(); <--- I do stuff with this.
But, of course, if some_data already exists (happens very frequently), LAST_INSERT_ID() returns 0. What is the best way to get the user_id based on the unique key some_data, in this case? Of course I can do a separate WHERE query, but not sure that is the most efficient.
From http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO users ( id, some_col ) VALUES (n,some_val)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), some_col=some_val;
Not an ignore but might do the job?
Edit:
To be clear, this will update some_col with some_val and then set the LAST_INSERT_ID to return the id of the duplicate row.
It could just as well be this if you didn't want to update any data on the duplicate but just set the LAST_INSERT_ID() call to give you what you want:
INSERT INTO users ( user_name ) VALUES ( 'bobloblaw' )
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID( id );
Edit 2:
Use a proc to do the work and get back the id
DELIMITER $$
CREATE PROCEDURE insert_test( val1 varchar(10), val2 varchar(10) )
BEGIN
INSERT INTO test.test_table ( col1, col2 ) SELECT val1, val2 FROM ( select 1 ) as a
WHERE NOT EXISTS (
select 1 from test.test_table t where t.col1 = val1
);
SELECT id FROM test.test_table where col1 = val1;
END $$
DELIMITER ;
I need an If, then, else query in mysql,
tried out the below,
if exists( select * from data_table where user_id =1 and link_id = 1) then update data_table set is_view = 1 where user_id = 1 else insert into data_table...
what is the correct way to do this?
if you only need to do this in mysql, then search insert on duplicate key. Or you can use a stored procedure. Check INSERT ... ON DUPLICATE KEY UPDATE Syntax
insert into data_table (user_id, link_id, other_column)
values (1, 1, 'value to insert or uodate')
on duplicate key update other_column='value to insert or update';
I am trying to populate a products table on MySQL with latest products, which are retrieved and stored in products_temp table.
So the method for this is straight forward, simply doing an INSERT to products from products_temp, as such:
INSERT INTO products ( select products_temp.* FROM products_temp )
Problem is, it results in a duplicate primary key error, because of the id from products_temp clashing with the id in products.
Can someone tell me how to fix this please?
I tried declaring the fields in the select statement without the id, but that results in "Column count doesn't match value count at row 1"
Any help would be appreciated.
Thanks!
You'll need to declare the columns except the ID on both the INSERT and the SELECT, since the number of fields need to match, and id (as you noticed) can't be inserted as is into the destination table.
INSERT INTO DestTable (field1, field2, field3)
SELECT field1, field2, field3 FROM SourceTable;
An SQLfiddle to test with.
EDIT: You could do it in a bit more hacky way to simplify the insert. You can create a trigger that simply forces the primary key to NULL on insert.
CREATE TRIGGER t_DT BEFORE INSERT ON DestTable
FOR EACH ROW
SET NEW.id = NULL;
then a copy from table to table can be done as simply;
INSERT INTO DestTable SELECT * FROM SourceTable;
Another SQLfiddle.
How about something like:
INSERT INTO products
(
select products_temp.* FROM products_temp
where key not in (select key from products)
)
I am trying to read value from a table them insert it into another table only if the staring that I am trying to insert does not already exist in the table.
I have tried to use the ON DUPLICATE KEY clause but I get a syntax issue that i am unable to fix.
this is my query
SELECT Field1 FROM RSF
INSERT INTO result_codes(result_code_title, created_by)
VALUES (Field1, '2')
ON DUPLICATE KEY UPDATE result_code_title = Field1;
The clause is INSERT INTO ... SELECT and not SELECT ... INSERT INTO. Therefore:
INSERT INTO result_codes( result_code_title, created_by )
SELECT Field1, '2'
FROM RSF
ON DUPLICATE KEY
UPDATE result_code_title = Field1;
I think that should work.
Since you only want to insert only if the string doesn't already exist; you should be better off using INSERT INGORE:
INSERT IGNORE INTO result_codes( result_code_title, created_by )
SELECT Field1, '2'
FROM RSF
Use INSERT IGNORE instead.
INSERT IGNORE INTO result_codes(result_code_title, created_by)
SELECT Field1, '2'
FROM RSF
It detects via a primary key or unique index, if a row already exists and doesn't attempt to insert if this is the case.