以下是我的SELECT语句的缩小版本。
SELECT
start_date,
IFNULL(@stop_date := HAIRY_CALCULATION(this_date, that_date)), '') as stop_date,
IF(@stop_date = '', 0, DATEDIFF(@stop_date, start_date)) as elapsed_days
FROM mytable
我想将elapsed_days
作为第二列,但这取决于@stop_date
变量的存在。
我怎么能做下面这样的事情,我在没有显示的情况下分配变量,所以我可以在后面的列计算中使用变量?
SELECT
DO_NOT_DISPLAY(@stop_date := IFNULL(HAIRY_CALCULATION(this_date, that_date), '')),
start_date,
IF(@stop_date = '', 0, DATEDIFF(@stop_date, start_date)) as elapsed_days,
@stop_date as stop_date
FROM mytable
答案 0 :(得分:0)
您始终可以SELECT
SELECT
来缩小要传播的数据范围:
SELECT stop_date, elapsed_days FROM
(SELECT
start_date,
IFNULL(@stop_date := HAIRY_CALCULATION(this_date, that_date)), '') as stop_date,
IF(@stop_date = '', 0, DATEDIFF(@stop_date, start_date)) as elapsed_days
FROM mytable) as subset
注意什么都没有"显示"除了你的客户。您正在谈论操纵结果集中的内容。
如果这是您经常做的事情,并且其背后的逻辑不太可能随意改变,您可能希望将其包装在视图中,以便您可以执行以下操作:
SELECT stop_date, elapsed_days FROM mytable_hairy_view
修改:这是一种可能的双程方法:
SELECT
start_date,
IF(stop_date = '', 0, DATEDIFF(stop_date, start_date)) AS elapsed_days
FROM
(SELECT
start_date,
HAIRY_CALCULATION(this_date, that_date) AS stop_date
FROM mytable) as stop_dates
答案 1 :(得分:0)
我找到了一个解决方法。也许不是最好的,但是:
SELECT
CONCAT(
-- -------- The following are just variable assignments for later use; they're not displayed in this column.
SUBSTRING(
(@stop_date := IFNULL(HAIRY_CALCULATION(this_date, that_date), '')),
0
),
-- -------- end of variable assignments for later use
start_date
) as start_date,
IF(@stop_date = '', 0, DATEDIFF(@stop_date, start_date)) as elapsed_days,
@stop_date as stop_date
FROM mytable