Insert data into table with result from another select query - mysql

I am seeking help on the following issue:
I have two tables
Table_1 columns are itemid, locationid, quantity
Table_2 columns are itemid, location1, location2, location3
I want to copy data from Table_1 (only quantity column) into Table_2 (into location1 column). The itemid are same in both the tables(Table_1 has duplicate item id's) so that's the reason I want to copy to a new table and keep all quantity in one single row with each location as a column. I am using the below query but it doesn't work
INSERT INTO
Table_2(location1)
(
SELECT qty
FROM Table_1
WHERE locationid = 1 AND Table_1.locationid = Table_2.locationid
)

If table_2 is empty, then try the following insert statement:
insert into table_2 (itemid,location1)
select itemid,quantity from table_1 where locationid=1
If table_2 already contains the itemid values, then try this update statement:
update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`)
SELECT sum(p1), sum(p2), sum(p3)
FROM `test`.`product`;

Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

Related

Getting gender count from one table and inserting to another in Mysql

I am trying to take gender stats from table 1
table_1
and table 2
table_2
and insert into 'gender' table
gender
using the command :
INSERT INTO gender(Male) VALUES ((SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'),(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male'))
and
INSERT INTO gender(Female) VALUES ((SELECT COUNT(*) FROM table_1 WHERE Gender = 'Female'),(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Female'))
But i keep getting an error: Column count doesn't match value count at row 1
The number of values passed and the number columns in the gender table don't match, hence the error.
Assuming the table gender has following columns -> gender, count_1, count_2
INSERT INTO gender(gender, count_1, count_2) VALUES ('Male', (SELECT
COUNT() FROM table_1 WHERE Gender = 'Male'),(SELECT COUNT() FROM
table_2 WHERE Gender = 'Male'))
INSERT INTO gender(gender, count_1, count_2) VALUES ('Female', (SELECT
COUNT() FROM table_1 WHERE Gender = 'Female'),(SELECT COUNT() FROM
table_2 WHERE Gender = 'Female'))
The error is telling your insert expects rows with one column, but your value has two.
INSERT INTO gender(Male) VALUES ( -- start of a row
-- Column 1
(SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'),
-- Column 2
(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male')
) -- end of a row
The problem is you have an extra set of parens making it one row with two columns. If you want to insert two rows, remove those parens.
INSERT INTO gender(Male) VALUES
(SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'), -- row 1
(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male'); -- row 2
The parens go around each row.

Insert into table with multiple rows in subquery

I want to have results in a table where the data comes from 3 different tables.
For that I have tried to execute this query:
INSERT INTO sometable (id,date)
VALUES
(
(SELECT id FROM table1
UNION
SELECT id FROM table2
UNION
SELECT id FROM table3)
,
(SELECT date FROM table1
UNION
SELECT date FROM table2
UNION
SELECT date FROM table3)
)
The result of this query is an error stating cannot insert multiple rows. Please help me to write this query correctly.
The INSERT ... SELECT syntax is different to the INSERT ... VALUES syntax. Also, you want to select both columns from each table at the same time:
INSERT INTO sometable (id, date)
SELECT id, date FROM table1 UNION
SELECT id, date FROM table2 UNION
SELECT id, date FROM table3

How to use select into statement?

I want to insert records from Table1 and Table2 into Table3 and my Table3 has Two columns:
studentId
subjectId
And I want to insert these 2 values from Table1(contains 1000 student Id's) and From Table2(contains 5 subjects). To achieve that I have used following query but it gave me error
Query:
INSERT INTO StudentSubject(studentId,subjectId)
SELECT studentId FROM Table1 UNION SELECT subjectId FROM Table2
But I got this error message:
Msg 120, Level 15, State 1, Line 1
The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
INSERT into StudentSubject(studentId,subjectId)
SELECT a.studentId,b.subjectId
FROM Table1 a CROSS JOIN Table2 b

What is the most efficient way to UPDATE existing rows and INSERT non-exist rows in a table-copy operation?

I have 2 tables:
stock:
pid name qty
--- ---- ---
1 aaaa 2
2 bbbb 3
1 aaaa 5
3 cccc 1
2 bbbb 2
stock_total:
pid name total_qty
--- ---- ---------
I can insert rows from stock table with the total qty to stock_total using this query
INSERT INTO stock_total (pid, name, total_qty)
SELECT pid, name, SUM(qty)
FROM stock
GROUP BY pid, name
The problem is, I will run the SQL above via cron job. So on the next execution, the SQL should UPDATE existing product and INSERT non-exist products.
It would be very inefficient if I loop over the SELECT results, check each row if exists in stock_total and do the INSERT or UPDATE.
Is there any simpler way for achieving this? perhaps by modifying the SQL above. Thanks.
Use DUPLICATE KEY UPDATE:
INSERT INTO TABLENAME(col1, col2)
VALUES (#value, ‘yyy’)
ON DUPLICATE KEY UPDATE col1 = #value
This for the update:
UPDATE stock_total
SET total_qty = SUM(s.qty)
FROM stock_total st
INNER JOIN stock s
ON st.pid = s.pid
AND st.name = s.name
WHERE s.pid = st.pid
GROUP BY s.pid
And this for the insert:
INSERT INTO stock_total
SELECT s.pid, s.name, SUM(s.qty)
FROM stock s
WHERE s.pid NOT IN (SELECT pid FROM stock_total)
GROUP BY s.pid, s.name
Should be fine, give it a try.
Why dont you call a Stored Procedure from the job?
In the SP in the block catch the DUPLICATE KEY exception and UPDATE. If no EXCEPTION is thrown it will INSERT.
merge is what you are searching for. Use it as follows -
merge into stock_total s " +
"using (select ? pid, ? name, ? total_qty from dual) d " +
"on (s.pid = d.pid and s.name = d.name and s.total_qty = d.total_qty) " +
"when matched then " +
"update set s.pid= d.pid, s.name = d.name, s.total_qty = d.total_qty" +
"when not matched then " +
"insert (pid, name, total_qty) " +
"values(d.pid, d.name, d.total_qty)" ;
EDIT(for mySQL):
MERGE INTO table_name WITH (HOLDLOCK) USING table_name ON (condition)
WHEN MATCHED THEN UPDATE SET column1 = value1 [, column2 = value2 ...]
WHEN NOT MATCHED THEN INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])
After some googling and experimenting with the answers here, I came up with this solution. It turns out that MySQL supports REPLACE INTO... and ...ON DUPLICATE KEY UPDATE. So my query would be like this:
REPLACE INTO stock_total
SELECT pid, name, SUM(qty)
FROM stock
GROUP by pid, name
or,
INSERT INTO stock_total
SELECT pid, name, SUM(qty)
FROM stock
GROUP by pid, name
ON DUPLICATE KEY UPDATE total_qty=VALUES(total_qty)
If a row exists on stock_total, the first query will DELETE then INSERT the new row,
and the second query will UPDATE the existing row.
Both query will only work if the table has a primary key or unique index:
CREATE TABLE stock_total (
pid INT NOT NULL,
name VARCHAR(20) NOT NULL,
total_qty INT NOT NULL,
UNIQUE (pid, name)
);
Documentation:
REPLACE syntax
INSERT ... ON DUPLICATE KEY UPDATE syntax

whats wrong with this mysql insert query?

insert into tblcustomermachine
(
select * from
((select vch_CustomerID from tblcustomer where tblcustomer.vch_CustomerID='Cust00001' )
union all
(select Rate from tblmachine)) as t );
that table contains 18 cols and this resultset also contains 18 rows yet it shows " Column count doesn't match value count at row 1" . why?
It looks like your table tblcustomermachine has more then the 1 column.
Like Simone answered, update your insert to INSERT INTO tblcustomermachine(col_1) SELECT ...
You may skip the column names during INSERT, however the SELECT needs to return the same amount of columns that the table holds.
AFAIK, you have to declare field name:
insert into tblcustomermachine (col_1, col_2, col_3, ... col_18) (
select t.field1, t.field2, t.field3, ... t.field18 from (
(select vch_CustomerID from tblcustomer where tblcustomer.vch_CustomerID='Cust00001')
union all (select Rate from tblmachine))
as t
);