SQL: can I insert some fields from other variables from another table?

SQL query

I wonder if I can write one sql INSERT to insert a row into a table where some of the fields come from variables and others from another table. Currently I select from tableA , save the fields in variables and then insert them into tableB . In the following example, I would like to get field1 , field2 and field3 from tableA , and the rest from variables. (MySQL)

 $sql = "SELECT field1, field2, field3 FROM tableA where product = 5"; 

php code

 $sql = "INSERT tableB SET fkey = 100, custid = 10, product = 5, field1 = '$field1', field2 = '$field2', field3 = '$field3' "; 
+4
source share
2 answers

Yes, you just mix literal values ​​and fields in select and insert:

 insert into tableB (fkey, custid, product, field1, field2, field3) select 100, 10, 5, field1, field2, field3 from tableA where product = 5 
+7
source
 INSERT INTO tableB (fkey, custid, product, field1, field2, field3) SELECT 100, 10, product, field1, field2, field3 FROM tableA WHERE product = 5 

You can, of course, replace the constants in the above expression with your variables.

+2
source

All Articles