簡體   English   中英

MySQL - SELECT 中計算列的訪問值

[英]MySQL - access value of calculated column in SELECT

我有一個查詢,它使用LEFT JOINGROUP_CONCAT生成一些計算列:

SET @this_year = YEAR(CURDATE());
SET @next_year = YEAR(CURDATE()) +1;
SET @last_year = YEAR(CURDATE()) -1;

SELECT
    m.id, m.name,

    GROUP_CONCAT(`se1`.`name` ORDER BY `se1`.`id` ASC SEPARATOR ', ') AS this_year_events,
    GROUP_CONCAT(`se2`.`name` ORDER BY `se2`.`id` ASC SEPARATOR ', ') AS next_year_months,
    GROUP_CONCAT(`se3`.`name` ORDER BY `se3`.`id` ASC SEPARATOR ', ') AS last_year_months

FROM month m

LEFT JOIN schedule_event se1 ON
    (m.start_date BETWEEN se1.start_date AND se1.end_date) OR
    (m.end_date BETWEEN se1.start_date AND se1.end_date)
    
LEFT JOIN schedule_event se2 ON
    (m.start_date BETWEEN se2.start_date AND se2.end_date) OR
    (m.end_date BETWEEN se2.start_date AND se2.end_date)
    
LEFT JOIN schedule_event se3 ON
    (m.start_date BETWEEN se3.start_date AND se3.end_date) OR
    (m.end_date BETWEEN se3.start_date AND se3.end_date)

GROUP BY `m`.`id`

結果如下所示:

id    name             this_year_events      next_year_events      last_year_events            
====================================================================================
1     January          Training, Planning    (NULL)                (NULL)               
2     February         (NULL)                (NULL)                Audit, Budget    
3     March            Team Meeting          Team Away Day         (NULL)

現在我想在這個查詢中添加另一列: active_year 此列將根據以下條件填充相應變量的值:

DEFAULT:
    active_year = @this_year

IF this_year_events IS NULL:
    active_year = @next_year

IF next_year_events IS NULL:
    active_year = @last_year

(如果滿足后續條件, active_year的值將覆蓋之前的值)

我嘗試為 3 個計算列分配一個變量,但它總是輸出NULL 我似乎無法弄清楚這一點。

你只想要case嗎?

with t as (
      <your query here>
     )
select t.*,
       (case when this_year_events is not null then @this_year
             when next_year_events is not null then @next_year
             else @last_year
        end) as active_year
from t;

您也可以在select中執行此操作:

select . . .,
       (case when max(se1.name) is not null then @this_year
             when max(se2.name) is not null then @next_year
             else @last_year
        end)
from . . . 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM