简体   繁体   English

MySQL - SELECT 中计算列的访问值

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

I have a query which produces some calculated columns using LEFT JOIN and GROUP_CONCAT :我有一个查询,它使用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`

The result looks like this:结果如下所示:

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)

Now I want to add another column to this query: active_year .现在我想在这个查询中添加另一列: active_year This column will be populated with the value of the corresponding variable based on the following condition:此列将根据以下条件填充相应变量的值:

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

(the value of active_year would overwrite the previous value if the subsequent condition is met) (如果满足后续条件, active_year的值将覆盖之前的值)

I have tried assigning a variable to the 3 calculated columns but it always outputs NULL .我尝试为 3 个计算列分配一个变量,但它总是输出NULL I just can't seem to figure this out.我似乎无法弄清楚这一点。

Do you just want case ?你只想要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;

You can also do this in your select :您也可以在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