SQL Insert Into multiple rows, but execute subquery only once - mysql

Im trying to optimize an INSERT INTO statement to use a subquery only once, as it is always the same value:
Heres my example code
INSERT INTO TABLE1 (id, number) VALUES
((SELECT other_id from TABLE2 WHERE somevalue = "test"), 12),
((SELECT other_id from TABLE2 WHERE somevalue = "test"), 13),
...,
...;
Not an sql-expert, but this doesnt look like a good approach, as the same subquery gets executed on every insert.
Is there an alternative solution?
also, i know i can select the ID beforehand and store it in a variable like this (pseudo-code-like):
$var = mysql_query("SELECT other_id from TABLE2 WHERE somevalue = 'test'")
mysql_query("INSERT INTO TABLE1 (id, number) VALUES
($var, 12),
($var, 13);")

INSERT
INTO table1 (id, number)
SELECT other_id, number
FROM table2
CROSS JOIN
(
SELECT 12 number
UNION ALL
SELECT 13
) q
WHERE somevalue = 'test'

Related

INSERT from SELECT statement, column count

Table1 has one column and table2 has three columns. The names are all unique.
INSERT INTO table2 (SELECT * FROM table1 WHERE name = 'Brian')
#1136 - Column count doesn't match value count at row 1
What is the easiest way to append NULL or empty strings to the results of the SELECT query?
I have tried this and many other variations:
INSERT INTO table2 (SELECT * FROM test WHERE name = 'Brian', '','')
INSERT INTO test2 ((SELECT * FROM test WHERE name = 'Brian') + '' , '')
The easiest way is to specify the column names in both source and target tables:
INSERT INTO table2 (col2) -- change col2 to the name of the column in table2 that will receive the values
SELECT col1 -- change col1 to the name of the column in table1
FROM table1
WHERE name = 'Brian';
All other than col2 columns in table2 will be set to null or their default values (if defined in the table's definition).
Even if col1 is the only column in table1, you should prefer SELECT col1 over SELECT *, because if you add any columns to the table SELECT * would stop working.

Not able to add multiple column against same ID in table

I have two tables x and y, x have the ID and many other columns, however y only have the ID similar as x table and then this ID is mapped to Many values
My Insert statement looks like this
INSERT INTO `table`
(`id`,
`other_name`)
VALUES
(select id from another_table where name = 'something'`,
('WALLETAB',
'SBTRADER',
'SBTRDACKING'));
expected result
1 | WALLETAB
1 | SBTRADER
1 | SBTRDACKING
I take ID from another table which already have data and this another table some different data associated with this table
You could fetch id from another table to be used in insert statement by using limit 1, something like:
select id from another_table where name = 'something' limit 1
However, to insert all 3 rows you will need a multiple insert in a single statement.
insert into `table` values
((select id from another_table where name = 'something' limit 1), 'WALLETAB'),
((select id from another_table where name = 'something' limit 1), 'SBTRADER'),
((select id from another_table where name = 'something' limit 1), 'SBTRDACKING');
See fiddle: https://www.db-fiddle.com/f/gYvrxdsDxVQPkZM2o8YRT1/1
It feels a lot of duplication. You can simplify it by either using variable or CTE. The following query utilizes CTE which only usable on mysql 8+:
insert into `table` (id, other_name)
with
other_id as (
select id from another_table where name = 'something'),
merged as (
select id, other_name from other_id join
(select 'WALLETAB' as other_name
union select 'SBTRADER'
union select 'SBTRDACKING')
as other_temp)
select * from merged;
The CTE above fetch the id on other_id. The union-select pairs is then used to create 3 rows containing 'WALLETAB', 'SBTRADER', and 'SBTRDACKING' respectively. Then both of them joined to get 3 rows with varying value on other_name but has id as 1.
See fiddle: https://www.db-fiddle.com/f/xgQta17bGphHAB81N2FNwX/1

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 insert into TABLE1 (field1,field2 'value','myval','currentdate') select(field1,field2) from TABLE2

I want to insert value from TABLE2 (2 field) into another TABLE1 (containing 5 field).
When I execute query:
insert into TABLE1 select (field1, field2) from TABLE2
My rest three fields became null.
I want to insert my new value like current date and new id in TABLE1.
How to do it?
Thanks in advance
TRY THIS
insert into TABLE1 (field1,field2 'value','myval','currentdate') select field1,field2,'your value','other value',NOW() from TABLE2
You can specify new columns next to field1 and field2.
If you are using MS Sql Server, for example:
Insert into table1
Select row_number() over(order by field1) as newID, field1, field2, Getdate(), value3
From table2

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