SQL在查询后插入表

时间:2018-10-23 17:40:41

标签: mysql

所以我不确定该如何处理。我有一张看起来像这样的桌子 [在此处输入图片描述] [1]

![1]:https://i.stack.imgur.com/k9Cl7.png

我需要从其他表中获取信息,并将其插入上表中。

获取我所需信息的查询如下:

select customerNumber, sum(quantityOrdered * priceEach) as orderTotal, curdate() as todaysDate 
from orders join orderdetails

where orders.orderNumber = orderdetails.orderNumber

group by orders.customerNumber

having orderTotal > 150000

我尝试使用:

insert into topCustomers( customerNumber, orderTotal, curdate())

在我的选择查询之前,这不是应该的工作方式。

任何指导都会很棒!

谢谢大家

1 个答案:

答案 0 :(得分:3)

INSERT INTO语句的括号中,插入要插入的字段名称。您没有名为CURDATE()的字段名,因此查询失败。相反:

insert into topCustomers( customerNumber, orderTotal, CustomerDate) 
select customerNumber, sum(quantityOrdered * priceEach) as orderTotal, curdate() as todaysDate 
from orders join orderdetails    
where orders.orderNumber = orderdetails.orderNumber    
group by orders.customerNumber    
having orderTotal > 150000

示例:

mysql> create table test2 (cdate date);
Query OK, 0 rows affected (0.32 sec)

mysql> INSERT INTO test2 (curdate());
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual tcorresponds to your MySQL server version for the right syntax to use near 'cte())' at line 1

mysql> INSERT INTO test2 (cdate) SELECT curdate();
Query OK, 1 row affected (0.07 sec)
Records: 1  Duplicates: 0  Warnings: 0