How to insert data from two tables into one table - sql

I need to insert values from two tables into one table. Eg Table 1 is outward and table 2 is product table. I need to insert values into outward table and from product table i have productname which needs to be inserted into outward table. My code is
INSERT INTO tbltrn_outward, tbltrn product(chalanno,godownsrno, igodownsrno,deladdress,outwarddate,productname,qty,boxes,rate,price,batchcombo,active,createdby,createdon,fyearsno)
VALUES('$chalanno','$godownsrno','$igodownsrno','$deladdress','$outwarddate','$productname','$qty','$boxes','$rate','$price','$batchcombo','$active','$createdby','$createdon','$fyearsrno')";

You should use insert into .. select from construct for this purpose like
INSERT INTO tbltrn_outward(col1,col2,col3, ...)
select col1,col2,col3,...
from tbltrn_product

There is the basic:
INSERT INTO tbltrn_outward(chalanno, godownsrno, ... )
SELECT
column1
, column2
, ...
FROM tbltrn_product

The syntax mentioned in question is not correct.
Below Query would help if fields in table1, table2 are unique and table3 contains all fields of table1 and 2:
INSERT INTO TABLE3 (SELECT * FROM TABLE1,TABLE2);
Refer fiddle here:http://sqlfiddle.com/#!2/e3cc4/1
Below query would help if fields overlap in table1 and 2:
INSERT INTO TABLE3 (SELECT TABLE2.FIELD1, TABLE1.FIELD2,
TABLE2.FIELD3, TABLE2.FIELD4
FROM TABLE1,TABLE2);
Refer fiddle here:http://sqlfiddle.com/#!2/479f4/1

Related

move all values from column in one table to new table and update third table with relation between those tables, PostgreSQL

I am using SQL after a long time and I have following:
I have existing table1 with columns id, name and a lot of other columns, it already contains rows.
I created empty table2 which only has columns id and name.
I created empty table3 which only has reference columns table1_id and table2_id.
Now I want to:
take all the values from column name in table1 (can be NULL, discard them in that case),
insert them as new rows into table2,
insert ids of the corresponding table1 and table2 rows into table3,
remove the column name from table1.
=> probably ALTER TABLE table1 DROP COLUMN name;, but I guess there may be a neater way to cut the result from step 1, transform it and paste as rows in step 2.
EDIT: I came up with something like (not tested yet):
SELECT table1.id, table1.name INTO results FROM table1;
FOR result1 IN
results
LOOP
WITH result2 AS (
INSERT INTO table2 (name) VALUES (result1.name) RETURNING id
)
INSERT INTO table3 (table2_id, table1_id) VALUES (result2.id, result1.id);
END LOOP;
ALTER TABLE table1 DROP COLUMN name;
EDIT:
I forgot to tell that if the name already existed in table2, I don't want to add it again (should be unique in table2), but I add the relation between the id from table1 and from the inserted/existing id from table2 into the table3.
EDIT:
I found we have source scripts for creating the database and I changed it there. Now I don't know how to get rid of this open question :(
For steps 1) & 2):
--Since you already have a table2
DROP TABLE table2;
--Create new table2 with data. Unless you are going to replace NULL with something
--discarding them would just end up with NULL again.
CREATE table2 AS SELECT id, name from table1;
Step 3). Not sure of the purpose of table3 as you would have matching id values between table1 and table2. In fact you could use that to set up a FOREIGN KEY relationship between them.
Step 4) Your solution: ALTER TABLE table1 DROP COLUMN name;
Not sure how you want to use it. If you want to run it as one-time transformation in one bulk, this could help (you can try the code on sqlfiddle):
CREATE TABLE table1 (
id int,
name varchar(9)
);
INSERT INTO table1 (
id,
name
)
VALUES
(1, 'A'),
(2, null),
(3, 'C'),
(4, null),
(5, 'E'),
(6, 'C')
;
CREATE TABLE table2 (
id SERIAL,
name varchar(9) UNIQUE
);
INSERT INTO table2 (name)
SELECT DISTINCT name
FROM table1
WHERE name IS NOT NULL
;
/*
-- This would be better option, but I was not able to test the merge/upsert function of PostgreSQL
INSERT INTO table2 (name)
SELECT name
FROM table1
WHERE name IS NOT NULL
ON CONFLICT table2_name_key DO NOTHING --merge/upsert, supports PostgreSQL 9.5 and newer
;
*/
CREATE TABLE table3 (
id_table1 int,
id_table2 int
) AS
SELECT
t1.id id_table1,
t2.id id_table2
FROM table1 t1
INNER JOIN table2 t2
ON t1.name = t2.name
;
--ALTER TABLE table1 DROP COLUMN name;
This could also be useful:
stackoverflow_1
postgresqltutorial
stackoverflow_2
postgresql documentation with PL/pgSQL code - suggestion you wrote in question is going much more this way

I need to insert the values from the second table to the first table whenewer the ID matches

I have 2 tables . Below is the fields description.
1st table Fields: EmployeeID, Name, EmployeeStatus, PreferredName
2nd table Fields: EmployeeID, PreferredName
I need to insert the values of PreferredName from 2nd table to the first table whenever EmployeeID matches. Currently all values of PreferredName in the 1st table are null. If no match by EmployeeID they should remain null . This is SQL Server.
I am trying something like :
insert into [Table1] PreferredName values
SELECT
[PreferredName]
FROM [Table2]
where [EmployeeID] in (SELECT EmployeeID FROM [Table1]
I think you actually want to UPDATE the table, not INSERT new data. For that, you can use an UPDATE with JOIN query:
UPDATE table1
SET table1.PreferredName = table2.PreferredName
FROM table1
JOIN table2 ON table2.EmployeeID = table1.EmployeeID
Demo on dbfiddle
you can use not exists keyword
insert into table1 (preferredname)
select t2.preferredname
from table2 t1 where
not exists (select 1 from table1 t1 where t1.preferredname = t2.preferredname)

How to insert a value from other table into the existing table

I am having two tables .
Table1 , Table2.
Table1 has name, age, salary.
Table2 has name,height, weight,Relevance,Weight_po etc.
. Both the tables has name as primary key.
Now I want to insert a two more new column in table 1 ie height, weight.
The values for height and weight has to fetch from Table2 where table1.name matches with table2.name.
Help me how to achieve this in postgres.
You can use select into statement and insert all data you want onto a NewTable with the structure you describe:
EDIT: Based on comment
Create table NewTable as
SELECT Table1.name,age,salary,height,weight
INNER JOIN Table2
ON Table1.name=Table2.name
Have you created height and weight columns in Table 1?
This will help to populate the values:
UPDATE Table1 t1
SET height= t2.height,weight=t2.weight
FROM Table2 t2
WHERE t1.name= t2.name
Tell me how it goes

How to store a table as two different tables using the AS function

I want to store table1 using the AS function as t1 and t2. How do I do this?
if you want to create table as well
SELECT * INTO table1
FROM t1;
If the table is already created
INSERT INTO Table1
SELECT* FROM t1;
INSERT INTO Table1
SELECT* FROM t2;
How to do INSERT into a table records extracted from another table
http://www.vbforums.com/showthread.php?529221-RESOLVED-create-table-as-select-in-MS-Access

SQL I want to duplicate record on insert

Without using a while or forloop, is there a way to insert a record two or more times on a single insert?
Thanks
INSERT INTO TABLE2 ((VALUE,VALUE)
SELECT VALUE,VALUE FROM TABLE1 )) * 2
You would need to CROSS JOIN onto a table with 2 rows. The following would work in SQL Server.
INSERT INTO TABLE2 ((VALUE,VALUE)
SELECT VALUE,VALUE
FROM TABLE1, (SELECT 1 UNION ALL SELECT 2) T(C)
If you have an auxilliary numbers table you could also do
SELECT VALUE,VALUE
FROM TABLE1 JOIN Numbers ON N <=2
--first create a dummy table with 2 records
INSERT INTO TABLE2 ((VALUE,VALUE)
SELECT VALUE,VALUE FROM TABLE1, dummytable ))
This is not an elegant way, but could work easily.
If you have a table with an high enough number of records you can do the cross join with a TOP clause
INSERT INTO TABLE2
SELECT VALUE,VALUE FROM TABLE1
cross join (select top 2 TABLE_DUMMY) as DUMMY
This works for MQ SqlServer, to let it work in other DBMS you should change the TOP with the keyword needed by your DBMS