如何在INSERT上的另一列的值中使用表列的动态值

时间:2014-06-11 05:02:54

标签: mysql insert-into mysql-logic select-insert

我正在做类似下面的事情。

INSERT INTO example_table
            (start_time,
             start_time_type,
             end_time,
             end_time_type,
             duration)
SELECT IF(start_time_type = 'now'
           OR start_time < " . CURRENT_TIME . ", " . CURRENT_TIME . ",
       start_time),
       start_time_type,
       IF(list_in = 'store', 0, ( IF(end_time_type = 'duration',
                                  " . CURRENT_TIME . " + duration * 86400,
                                  end_time
                                  ) )),
       IF(list_in = 'store', '', 'duration'),
       IF(list_in = 'store', end_time - start_time / 86400, duration)
FROM   bulk_listings
WHERE  .....

现在您可以看到持续时间,我想要处理start_timeend_time的结果值;但显然下面的代码不起作用,因为它将对我假设的列的当前值起作用,并且不会使用我想要的结果值

有没有办法做我想做的事?

1 个答案:

答案 0 :(得分:1)

您需要使用计算值列创建子查询:

SELECT start_time, start_time_type, end_time,
       IF(list_in = 'store', '', 'duration'),
       IF(list_in = 'store', end_time - start_time / 86400, duration)
FROM (SELECT IF(start_time_type = 'now'
           OR start_time < " . CURRENT_TIME . ", " . CURRENT_TIME . ",
       start_time) AS start_time,
       start_time_type,
       IF(list_in = 'store', 0, ( IF(end_time_type = 'duration',
                                  " . CURRENT_TIME . " + duration * 86400,
                                  end_time
                                  ) )) AS end_time,
       duration,
       list_in
FROM   bulk_listings
WHERE ...) AS SUBQUERY