Select and Insert with a condition? [duplicate] - mysql

I would like to insert new values into a table where one of the values is being selected from another table with a condition, and the other value is a constant (hardcoded)
this command gives a syntax error
INSERT INTO table1 (itemId, reservedId) VALUES (SELECT id FROM table2 WHERE condition, 213) ;
error message : syntaxe error at line 2

The syntax is INSERT . . . SELECT:
INSERT INTO table1 (itemId, reservedId)
SELECT id, 123
FROM table2
WHERE condition ;
No VALUES is needed.

You can't mix values and select statements like this, as you've seen. You could, however, select the literal values you want to insert from the same table (note that you should not have a values clause - it's replaced by the select statement):
INSERT INTO table1 (itemId, reservedId)
SELECT id, 213 FROM table2 WHERE condition;

You can either use
insert into yourtable(...) values(...)[, (...)...]
or
insert into yourtable(...) select ...
Your mistake was that you mixed up the two syntaxes. You will not need values(...) here wrapped around your select:
INSERT INTO table1 (itemId, reservedId)
SELECT id, 213
FROM table2
WHERE condition;
Notice that 213 is a value for reservedId and has nothing to do in the where clause.

Related

How to merge 2 tables in mySQL [duplicate]

I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
(SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
I tried but get a syntax error message.
What would you do if you want to do this?
No "VALUES", no parenthesis:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
You have two syntax options:
Option 1
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
Remove both VALUES and the parenthesis.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.
Also, you really don't need the parentheses around the select statement.
From msdn:
Multiple-record append query:
INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression
Single-record append query:
INSERT INTO target [(field1[, field2[, …]])]
VALUES (value1[, value2[, …])
Remove VALUES from your SQL.
Remove "values" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.
If the column names are the same in both tables, your query would be like this:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1
FROM Table1
GROUP BY LongIntColumn;
And it would work without an alias:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn)
FROM Table1
GROUP BY LongIntColumn;
Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.
Open both recordsets
Extract the data from the first table (SELECT blablabla)
Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
Close both recordsets
This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)
inserting data form one table to another table in different DATABASE
insert into DocTypeGroup
Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType
from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup
Do you want to insert extraction in an existing table?
If it does not matter then you can try the below query:
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 INTO T1 FROM Table1
GROUP BY LongIntColumn1);
It will create a new table -> T1 with the extracted information

insert when one value is selected from other table

I would like to insert new values into a table where one of the values is being selected from another table with a condition, and the other value is a constant (hardcoded)
this command gives a syntax error
INSERT INTO table1 (itemId, reservedId) VALUES (SELECT id FROM table2 WHERE condition, 213) ;
error message : syntaxe error at line 2
The syntax is INSERT . . . SELECT:
INSERT INTO table1 (itemId, reservedId)
SELECT id, 123
FROM table2
WHERE condition ;
No VALUES is needed.
You can't mix values and select statements like this, as you've seen. You could, however, select the literal values you want to insert from the same table (note that you should not have a values clause - it's replaced by the select statement):
INSERT INTO table1 (itemId, reservedId)
SELECT id, 213 FROM table2 WHERE condition;
You can either use
insert into yourtable(...) values(...)[, (...)...]
or
insert into yourtable(...) select ...
Your mistake was that you mixed up the two syntaxes. You will not need values(...) here wrapped around your select:
INSERT INTO table1 (itemId, reservedId)
SELECT id, 213
FROM table2
WHERE condition;
Notice that 213 is a value for reservedId and has nothing to do in the where clause.

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.

MYSQL syntax for inserting data to a table from another one which are not same form

It could be obvious but since I don't have any experience I cannot figure out how to do. Here is the question; say I have table2 with fields id,name, time, price and explanation.Also, there is an other table1 which has name, time and price. I want to insert data from table1 if price is higher than some threshold, while doing so as an explanation I want "The price is above threshold". Can anyone suggest me a way to do so? Thanks in advance.
Try this...
INSERT INTO `table2` (`name`, `time`, `price`, `explanation`)
SELECT `name`, `time`, `price`, 'The price is above threshold'
FROM `table1`
WHERE `price` > 100
INSERT table1 (name, time, price)
SELECT name, time, price
FROM table2
WHERE price > 120
You use an INSERT statement and list the fields you wish to insert into, followed by the SELECT statement you are going to use to populate the fields with. Here's a link: http://dev.mysql.com/doc/refman/5.5/en/insert.html.
Example:
INSERT INTO insert_tablename (field1, field2, field3)
SELECT field1, field2, field3
< The rest of your select statement >
NSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables. For example:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
The following conditions hold for a INSERT ... SELECT statements:
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

MySQL direct INSERT INTO with WHERE clause

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,...)