如何将这两个查询合并为一个INSERT INTO?

时间:2017-09-27 06:00:45

标签: php mysql sql-server

有人能告诉我如何将这两个查询合并到一个INSERT INTO查询中?

$query1 = "INSERT INTO `monthly_income`(`Year`, `Month`) VALUES (2017, 'September')";
$query2 = "INSERT INTO `monthly_income`(`totalincome`) SELECT SUM(Income) FROM `eventincome` WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-30'";

这里我想将所有这些值插入表“monthly_income”中的一行。在Query2中,我从名为“eventincome”的单独表格生成两个日期之间的总收入。 “monthly_income”表中包含[Year,Month,totalincome]列。而且“eventincome”表中有[eventDate,eventTitle,Earnings,Expenses,Income]列。那么我如何加入这两个查询来在

中使用它
  

mysqli_query($ conn,参数)

:) PS:我想从同一行中的那些查询中设置这些值,而不是通过这两个INSERT INTO创建两个单独的行。这就是为什么我想加入/合并/合并(无论如何)这两个查询:)

2 个答案:

答案 0 :(得分:0)

试一试

$query2 = "INSERT INTO `monthly_income`(`totalincome`,`Year`, `Month`) SELECT SUM(Income),2017 as Year, 'September' as Month FROM `eventincome` WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-30'";

答案 1 :(得分:0)

将第一个查询中的值作为常量添加到第二个查询...

"INSERT INTO monthly_income(Year, Month,totalincome) SELECT 2017, 'September',SUM(Income) FROM eventincome WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-3'";