I have to run two insert statements in two different tables.
The sqls are as under :
INSERT INTO Table1 ('t1_name', 't1_class') VALUES ('Joe','8');
Table1 has an autoincremental ti_id column
INSERT INTO Table2 ('t2_ti_id','t2_course') VALUES(< 'ti_id' from Table1 call >,
'English'),(< 'ti_id' from Table1 call >, 'Math').
So end result should have been, such that the autoincremental id set for table1 query is used in the table2 query
Table1
t1_id ti_name t1_class
1 Joe 8
Table2
t2_id t2_t1_id t1_course
1 1 English
2 1 Math
t1_id and t2_t1_id have a foreign key setup
Please tell me how to make thecalls from the same sql, so that i dont have to make a seperate perl script for this
Thanks in advance
Use last_insert_id()
Try this:
INSERT INTO Table1 (t1_name, t1_class) VALUES ('Joe','8');
SET #t1id = SELECT LAST_INSERT_ID();
INSERT INTO Table2 (t2_ti_id, t2_course)
VALUES (#t1id,'English')
Related
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
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 have two tables t1 and t2. t1 has duplicated values. I need to insert all records from t1 to t2, but I don't want duplicates to occur in t2. I tried the following command which seems to me correct and no syntax error when I run it but the problem, it has 0 effect. No records from t1 inserted in t2.
insert into test.t2 (name2)
select name1 from test.t1 where NOT EXISTS (select name2 from test.t2);
Can anybody help ?
insert into test.t2(name2)
select distinct name1 from test.t1 where name1 NOT IN(select name2 from test.t2);
OR
insert into test.t2(name2)
select distinct name1 from test.t1 t1 where NOT EXISTS(select name2 from test.t2 t2 where t1.name1=t2.name2);
You can create a unique index (of one or more columns) and then use the MySQL replace command.
CREATE UNIQUE INDEX unique_name2 ON t2 (name2);
REPLACE INTO t2 (name2) values ($name1);
...
You've go two options here, one involves not duplicating the data on your insert, the second being to ignore duplicates when inserting.
To de-duplicate from the SELECT call you'd use `DISTINCT:
INSERT INTO test.t2 (name2) SELECT name1 FROM test.t1 WHERE name1 NOT IN (SELECT name2 FROM test.t2)
You can also add a UNIQUE index to avoid this problem in the first place:
ALTER TABLE t2 ADD UNIQUE INDEX index_name2 (name2)
Note that you will get an error if there is already duplicate data in t2, so you may have to clean it up beforehand.
Then you can add data with the IGNORE option:
INSERT IGNORE INTO test.t2 (name2) SELECT name1 FROM TEST.t1
The unique index approach will guarantee uniqueness.
I need to insert data from user to another user and when write this statement
.....
insert into trep12.jobhead
select
*
from
wsfin04.jobhead
where
wsfin04.jobhead.job_no not in (select job_no from trep12.jobhead)
and wsfin04.jobhead.CHASS_NO not in (select CHASS_NO from trep12.jobhead)
and rdate between '01-jul-15'
and '01-oct-15'
and job_type = 1;
.....
the result is 0 rows created.
this should do it:
INSERT IGNORE INTO test.t2 SELECT name2 FROM test.t1
Selects from one table and inserts into another.
I am new to mysql. I have a problem in inserting record to table1 if it does not exist in table2.I have 2 tables table1 and table2 in the form:
table1
dep_id start stop modified deleted
1 23456789 167921525 Yes No
2 34567812 345678145 Yes No
3 32789054 327890546 No No
table2
start stop modified deleted
23456789 167921525 No No
34567823 345678145 No No
32789053 727890546 No No
I am trying to insert values into table1's start and stop field values only if it does not exist in table2's "start" and "stop" columns. If it exists the I need to throw an error.
These tables do not have a primary key foreign key relationship.
I apologize for not knowing correct syntax but I have to do something like this in mysql and PHP.
Replace Into into table1 set 'start'=> $start,'stop' => $stop
(select 'start','stop' from table2 where table1.start and table1.stop not in table2.start and table2.stop);
How do I query these 2 tables to check if Table1.start and Table1.stop fields do not match with Table2.start and Table2.stop before inserting to table1?
You can do:
INSERT INTO table1 (start, stop)
SELECT a.*
FROM (SELECT 123456789 start, 234567890 stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE b.start IS NULL
Where 123456789 and 234567890 are your input values for start and stop respectively.
Then you can check it with rowCount or num_rows_affected based on what DB interface you're using (PDO, mysqli, etc.). If it's 0, then no record was inserted, otherwise, the insert occurred.
SQLFiddle Demo
I think this is what you want. This takes two values, $start and $stop, and only does the insert if it does not exist in table2:
insert into table1 (start, stop)
select *
from (select $start as start, $stop as stop) t
where not exists (select 1 from table2 where start = $start and stop = $end)
With parameterized values:
INSERT INTO table1 (start, stop)
SELECT a.*
FROM (SELECT ? start, ? stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE b.start IS NULL
This works but we do the insert through SQL statements.
Now, what would be the solution to insert the records by Interface? That is without SQL statement, with the restriction proposed in the problem.
I have two tables:
t1(mainid, parentid)
t2(mainid, parentid)
How would I copy the values of t1.mainid to t2.parentid?
I tried using:
SELECT mainid INTO t2 FROM t1
but it does not work.
Try the INSERT ... SELECT syntax:
INSERT INTO t2(parentid) SELECT mainid FROM t1
In case the mainid in t2 is also auto increment
INSERT INTO t2(parentid) SELECT mainid FROM t1
INSERT INTO t2 SELECT 0,mainid FROM t1
INSERT INTO tbl_name [(col_name,...)] SELECT ....
INSERT-SELECT
The following solution
INSERT INTO t2(parentid) SELECT mainid FROM t1
will work, as long as t2(mainid) has a default value set. Check it.
When you insert into a table, you have to think about the fact that you are inserting an entire row in the table, not just the value of one column. Even if some of the columns have default values, it is helpful to think about inserting an entire row into a table.
So to cross the mainid column's values from t1 into t2's parentid column, you could do the following:
INSERT INTO T2 SELECT 0,mainid FROM T1
But for every mainid value in T1, you will transfer a 0 and the manid value to make up
a t2 row. If t2 has a unique constraint, you won't be able to solve the problem this way.