php - 将 mysql 查询的结果插入现有表

标签 php mysql sql

我有一个包含时间戳和其他值的现有表,我想为表中的每一天创建虚拟时间戳

例如

    timestamp           phase_1 phase_2 phase_3
2014-03-04 12:00:00   0       0        0
2014-03-05 02:00:00   0       0        0
2014=03-06 01:00:00   0       0        0
2014-03-07 00:00:00   0       3        1

应该导致

timestamp           phase_1 phase_2 phase_3
2014-03-04 00:00:00   0       0        0     --<< new
2014-03-04 12:00:00   0       0        0
2014-03-05 00:00:00   0       0        0     --<< new
2014-03-05 02:00:00   0       0        0
2014-03-06 00:00:00   0       0        0     --<< new
2014-03-06 01:00:00   0       0        0
2014-03-07 00:00:00   0       3        1

下面的查询工作正常

`select * from Table1

right join

(select
        `timestamp`
      , phase_1
      , phase_2
      , phase_3
from Table1

union

select
        date(`timestamp`)
      , 0
      , 1
      , 2
from Table1

order by 
        `timestamp`) `

但我无法将结果插入现有数据库

使用下面的查询

`INSERT into Table1

select * from Table1

right join

(select
        `timestamp`
      , phase_1
      , phase_2
      , phase_3
from Table1

union

select
        date(`timestamp`)
      , 0
      , 1
      , 2
from Table1

order by 
        `timestamp`) `

我认为这是正确的,但我得到了

: Every derived table must have its own alias:  error which i am not sure on how to solve

这是 fiddle enter link description here

此外,是否可以插入表中根本不存在的虚拟时间戳和日期值?

假设表中第一行和最后一行之间有两天,并且表中没有这几天的时间戳,是否可以将这两个日期添加到表中。

我想尽可能避免使用触发器和过程,因为我对它们一点也不熟悉,而且由于表格是动态生成的,我认为不可能使用它们。

最佳答案

您必须为 UNION 使用别名,但您还必须为正确的联接提供 JOIN 条件。可能您想使用:

INSERT INTO Table1
select a.* from Table1    
right join    
(
    select
        `timestamp`
      , phase_1
      , phase_2
      , phase_3
    from Table1

    union

    select
        date(`timestamp`)
      , 0
      , 1
      , 2
    from Table1

    order by 
        `timestamp`
) as a
ON DATE(a.timestamp) = DATE(Table1.timestamp)

备注:

What is the difference between Left, Right, Outer and Inner Joins?对不同的连接提供了很好的解释。

外部连接需要连接条件,没有条件的内部连接与交叉连接相同,cartesian product两个表(大多数时候人们想避免这种情况 - 但永远不会)。

如果您使用 SELECT 语句,它在连接中作为单独的 SELECT 语句工作得很好,那么这个 SELECT 语句的结果会变成一个派生表,您必须给这个派生表一个名字,这样您就可以使用派生表的列。

我希望现在会更清楚一些。

关于php - 将 mysql 查询的结果插入现有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226805/

相关文章:

PHP和MySQL高流量解决方案

php - 在 ajax 响应文本中发送 json 字符串和 html 数据 - 如何?

php - 如何从数据库中的表中获取所有数据并使用 php 显示它?

找不到 mysql_upgrade

mysql - 如何优化这个复杂的查询?

php - DynamoDB updateItem 创建新记录

php - PHP框架适合什么样的项目?

MySQL - 使用 where、count 和having 两个表的 SQL 选择查询

java - 在JOOQ中将RDS数据写入磁盘

sql - 过滤掉 SELECT 中重复的后续记录