SQL问题
我想知道我是否可以编写单个sql INSERT
语句来将一行插入到表中,其中某些字段来自变量而其他字段来自另一个表。目前,我从tableA
中选择,将字段存储在变量中,然后将其插入tableB
。
在以下示例中,我想从field1
获取field2
,field3
和tableA
,其余来自变量。 (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' ";
答案 0 :(得分:7)
是的,您只需在select和insert中混合文字值和字段:
insert into tableB (fkey, custid, product, field1, field2, field3)
select 100, 10, 5, field1, field2, field3
from tableA
where product = 5
答案 1 :(得分:2)
INSERT INTO tableB (fkey, custid, product, field1, field2, field3)
SELECT 100, 10, product, field1, field2, field3 FROM tableA
WHERE product = 5
当然,您可以使用变量替换上述语句中的常量。