MySQL direct INSERT INTO with WHERE clause - mysql

I tried googling for this issue but only find how to do it using two tables, as follows,
INSERT INTO tbl_member
SELECT Field1,Field2,Field3,...
FROM temp_table
WHERE NOT EXISTS(SELECT *
FROM tbl_member
WHERE (temp_table.Field1=tbl_member.Field1 and
temp_table.Field2=tbl_member.Field2...etc.)
)
This worked for one scenario,But now my interest is to upload data directly from the program itself without using two tables. What i want is to upload the data which is not in the table. The sql i had in my head was like the following,
INSERT INTO tbl_member (SensorIdValue, DataTimeValue, DataInValue, IncompleteValue, SpiValue, InfoValue)
VALUES ('Sensor.org', '20121017150103', 'eth0','','','')
WHERE (SensorIdValue != 'Sensor.org'AND DataTimeValue != '20121017150103'AND DataInValue != 'eth0'AND IncompleteValue != ''AND SpiValue != ''AND InfoValue != '');
But it's wrong.. may i know the proper way of doing it please, Thank you very much :)

INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
The first syntax is already correct.

you can use UPDATE command.
UPDATE table_name SET name=#name, email=#email, phone=#phone WHERE client_id=#client_id

INSERT syntax cannot have WHERE but you can use UPDATE.
The syntax is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:
INSERT INTO tbl_member
(Field1,Field2,Field3,...)
SELECT a.Field1,a.Field2,a.Field3,...
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a
LEFT JOIN tbl_member AS b
ON a.Field1 = b.Field1
WHERE b.Field1 IS NULL
The record to be inserted is in the new value fields.

Example of how to perform a INSERT INTO SELECT with a WHERE clause.
INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2

merge into table2 chg
using table1 src on src.id = chg.id
when not matched then
insert (chg.id, chg.desc)
values (src.id, src.desc)
when matched then
update set chg.desc = src.desc;

The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Related

MySQL: how to update column using value before change

There is a table with three column: id, field1, field2.
And there is a row: id=1, field1=1, field2=1.
Run a update SQL: UPDATE my_table SET field1=field2+1, field2=field1+1 WHERE id=1;
I expected the result is: id=1, field1=2, field2=2. But in fact I got: id=1, field1=2, field2=3. Because when calculating field2=field1+1, the value of field1 has changed!
I figure out a SQL to solve this problem:
UPDATE my_table dest, (SELECT * FROM my_table) src
SET dest.field1=src.field2+1, dest.field2=src.field1+1
WHERE dest.id=1;
However I want to insert a record, and if the row was existed then do a update just like above.
INSERT INTO my_table (id, field1, field2) VALUES(1, 1, 1)
ON DUPLICATE KEY UPDATE
field1=field2+1, field2=field1+1;
This SQL has problem same as the first SQL. So how can I do this update using the value before change with ON DUPLICATE KEY UPDATE clause?
Thanks for any help!
Couldn't think of anything else but a temp variable. However, couldn't think of a way to make SQL syntax work, other than this:
set #temp = 0;
update test.test set
f1 = (#temp:=f1),
f1 = f2 + 1,
f2 = #temp + 1
where id = 1;
Hope this helps, and hope even more it helps you find a better way :)
I find a trick way to do this.
Use the IF clause to create temp variable. Field update use temp variable to calculate.
INSERT INTO my_table (id, f1, f2) VALUES(1, 1, 1)
ON DUPLICATE KEY UPDATE
id=IF((#t1:=f1 & #t2:=f2), 1, 1), f1=#t2+1, f2=#t1+1;
There is some point to notice:
The performance is a bit slow. Especially copy TEXT value to temp variable.
If field id need to use IF clause, the expr will be more complicated like:
((#t1:=f1 & #t2:=f2) || TRUE) AND (Your Condition)

SQL select and insert if not exists

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.

How to insert values from a table only if they do not exist already using mysql?

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.

Insert data from another table with a loop in mysql

I could solve it with php or some other language but I am keen to learn more SQL.
Is there a way to solve this:
I have two tables (and I can't change the structure), one content with some data and the other content_info with some additional information. They are related that way: content.id = content_info.content_id.
What I would like to do: If there is no dataset in content_info but in content, I would like to copy it over, that at the end there are the same number of datasets in both tables. I tried it that way, but unfortunately it doesn't work:
...
BEGIN
(SELECT id, ordering FROM content;)
cont:LOOP
#cid = SELECT content_id FROM content_info WHERE content_id = (id)
IF #cid != (id) THEN
INSERT INTO content_info SET content_id = (id), ordering = (ordering)
ITERATE cont;
END IF;
END LOOP cont;
END
..
Has someone an idea, or isn't it possible at the end? Thanks in advance!
You can use INSERT IGNORE to insert new rows but do nothing if there's already a row in the table that would cause a duplicate entry error.
INSERT IGNORE INTO jos_content_frontpage (content_id, ordering)
SELECT id, ordering FROM jos_content
Seems like you are looking for the INSERT ... SELECT syntax. Any select can be inserted into a table provide you format the data to match the target table.
Also, your INSERT syntax is incorrect, looks like you are using the UPDATE syntax.
INSERT INTO table (field1, field2, field3) VALUES ('1','2','3');
INSERT INTO table (field1, field2, field3) SELECT field1, field2, field3 FROM ...
I will give example for one field only, the id field. you can add other fields too:
insert into content_info(content_id)
select content.id
from content left outer join content_info
on (content.id=content_info.content_id)
where content_info.content_id is null
another way
insert into content_info(content_id)
select content.id
from content
where not exists (
select *
from content_info
where content_info.content_id = content.id
)

Conditionally insert a row

I'd like to insert a row into table A, but only if another row in table B exists. For example something like this...
IF EXISTS (SELECT * FROM B WHERE id=1)
INSERT INTO A
(id, value1, value2)
VALUES (1, 'foo', 'bar')
However that doesn't work. What will?
INSERT INTO A (value1, value2, value3)
SELECT 'foo', 'bar', 'foo' FROM B WHERE ID = 1
One potential problem here is if your condition is met more than once it will insert as many rows so adjust your query to that, but it will do what you want, only insert if the conditions on the select are met.
Have a look at this piece of MySQL manual, it gives an example with SELECT, but maybe INSERT would also work in a similar fashion?