How to use dynamic value of table column in the value of another column on INSERT

92 Views Asked by At

I'm doing something like the below..

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  .....

Now as you can see for the duration, I am wanting to work on the resulting value of the start_time and end_time; however obviously the code below will not work as that will work on the current value of the column I assume and won't use the resulting value I am wanting.

Is there any way to do what I want?

1

There are 1 best solutions below

2
On BEST ANSWER

You need to create a subquery with your computed values columns:

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