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.
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 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')
How can we copy data from one table into another table which doesn't exist in the first one. In table one of the column is primary key.
INSERT INTO table SELECT * FROM db2.table;
ERROR 1062 (23000): Duplicate entry '100001' for key 'id_UNIQUE'
You can use the predicate NOT IN to do so like this:
INSERT INTO table1
SELECT *
FROM db2.table2
WHERE table1ReferenceID NOT IN(SELECT id_UNIQUE FROM table1);
This will checks whether this table1ReferenceID found in the first table or nor. Therefore, the SELECT clause will select all the rows from the second tables except those that is already presented in the first table table1.
Note that: the column table1ReferenceID is the reference of the id_UNIQUE in the second table.
Other alternatives for this, is to LEFT JOIN as suggested by #HamletHakobyan's answer and NOT EXISTS.
See it in action
Try this:
INSERT INTO table
SELECT T1.*
FROM db2.table T1
LEFT JOIN table T2
ON T1.Id = T2.Id
WHERE T2.Id IS NULL;
WHERE [primary_key_table1] not IN (SELECT [primary_key_table2] FROM [table2])
so i suggest something like
INSERT INTO table (SELECT * FROM db2.table WHERE id NOT IN (SELECT id FROM table));
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.
Please help me in resolving this query.
Table t1 having "t1c1" and "t1c2" columns.
Table t2 having "t2c2" and "t2c2" columns.
I have to insert values into t3 table having "t3c1","t3c2",t3c3" columns.
The condition is that "t3c2" column values should be populated from "t1c2" column and "t3c3" column should be populated from "t2c2" column and "t3c1" should be populated from cursor values.
Can someone help in this? Is this possible?
This should work:
INSERT INTO t3 (t3c1, t3c2, t3c3)
SELECT currval, t1.t1c2, t2.t2c2
FROM t1, t2;
If you need to match only certain rows in t1 and t2, you can add:
WHERE t1.t1c1 = 'value'
AND t2.t2c1 = 'value';
I don't now if i understand your question.
May be some code in SQL would be better than other desctiption. If i undestand you have this view
CREATE VIEW t3 as SELECT t1c2 AS t3c2, t2c2 AS t3c3, rowid (oid ... or something) AS t3c1 FROM t1,t2 WHERE ....
Then you can make a triger INSTEAD OF
CREATE TRIGGER t3_insert INSTEAD OF INSERT ON t3 AS BEGIN
INSERT t1 .... VALUES (NEW.t3c1 .....)
.......
END;
or if t3 is regular table and you want to modify your data in t3 then use trigger AFTER INSERT (UPDATE,DELETE)
Be more specific, you can will receive a better solution.
insert into t3(t3c1,t3c2,t3c3)
(select curval,t1.t1c2,t2.t2c2 from t1 left outer join t2 on t1.col=t2.col)