Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add static value when doing INSERT INTO with SELECT in a MySQL query?

I have two MySQL tables a and b with fields x and y. Table b has 1 extra field z. Table a is in database db1 and b is in db2. I want to copy x and y from a to b and set a static value for z. How can I do that ?

db1.a.x -> db2.b.x db1.a.y -> db2.b.y 4 -> db2.b.z 

So far I have:

"INSERT INTO db2.b (x,y) SELECT x,y FROM db1.a" 

How do I set db2.b.z to 4 ? I do not want to set a permanent default variable for the table.

like image 687
JasonTS Avatar asked Jan 30 '12 04:01

JasonTS


People also ask

How do I assign a static value to a select query?

Selecting Static Values Static values can be inserted into a resultset returned from a SELECT query as another column. Simply use the static value as a column to select, and the query will return a column where the name of the column is the static value, and every row in that column will return that same static value.

How use select and insert together in MySQL?

The following is the basic syntax that illustrates the use of the INSERT INTO SELECT command in MySQL. If we want to copy all data from one table into another table, we can use the below statement: INSERT INTO table_name2. SELECT * FROM table_name1.

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

Can you insert data in selected columns using insert into statement?

You can still insert records into the destination table with specifying column names in the INSERT INTO SELECT statement.


2 Answers

SELECT 4 will give you 4, so try:

INSERT INTO db2.b (x,y,z) SELECT x,y,4 FROM db1.a 
like image 106
xdazz Avatar answered Sep 21 '22 20:09

xdazz


INSERT INTO db2.b (x, y, z) SELECT x, y, 4 FROM db1.a; 
like image 30
pilcrow Avatar answered Sep 20 '22 20:09

pilcrow