Query for Insert into using values from other table

Natalya Bernadskaya :

I have two tables Table1 ( with fields A1 | B1 | C1 ) and Table 2 with fields A2 | B2.

I need to insert into Table1 strokes with values A1 = const, B1 = const and C1 - value of A2 from Table2, where B2 = const

Table1

A1 | B1 | C1

Table 2

A2 | B2
1  | 3
2  | 3
6  | 3
4  | 6
5  | 6

After the query, where A1 = 0, B1 = 1, B2 = 3 we should get:

Table1

A1 | B1 | C1
0  | 1  | 1
0  | 1  | 2
0  | 1  | 6

I suppose that it will look like this:

INSERT INTO Table1 (‘A1’,’B1’,’C1’) VALUES (0, 1, SELECT A2 FROM Table2 WHERE B2=”3”)
GMB :

You seem to be looking for the standard INSERT ... SELECT syntax:

INSERT INTO Table1 (A1, B1, C1) 
SELECT 0, 1, A2 FROM Table2 WHERE B2 = 3

Your original attempt does not work because VALUES() takes tuples of scalar values (each tuple represents one row), while the query returns multiple rows.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407712&siteId=1