如何将数组设置为mysql用户变量

Chr*_*s B 8 mysql arrays

我没想到会发现这么困难,但我试图在MySQL中设置一个用户变量来包含一个值数组.我不知道如何做到这一点所以尝试做一些研究,并且很惊讶找不到答案.我试过了:

SET @billable_types = ['client1','client2','client3'];
Run Code Online (Sandbox Code Playgroud)

原因是我想在稍后的语句中使用该变量:

SELECT sum((time_to_sec(timediff(tlg.time_stop, tlg.time_start))/3600)) as billable_hours
    from mod_tmlog_time_log tlg, mod_tmlog_task_list mttl
    where date(tlg.time_start) >= @time_start
          and date(tlg.time_stop) <= @time_stop
          and mttl.type IN (@billable_types)
            and tlg.task_id = mttl.id
    group by start_date
    order by start_date desc;
Run Code Online (Sandbox Code Playgroud)

非常感谢你的帮助.


快进一段时间,我最终得到了以下快速而肮脏的解决方案,这并没有给我在代码中其他地方重新使用数组的灵活性,但是,这是一个不可完成的管理任务,所以我不想再花费更多时间就可以了.

SELECT WEEKDAY(tlg.time_start) AS day_of_week, date(tlg.time_start) as start_date,
                            sum((time_to_sec(timediff(tlg.time_stop, tlg.time_start))/3600)) as billable_hours
                    from mod_tmlog_time_log tlg, mod_tmlog_task_list mttl
                    where date(tlg.time_start) >= @time_start
                          and date(tlg.time_stop) <= @time_stop
                          and mttl.type IN ('c1','c2','c3')
                            and tlg.task_id = mttl.id
                    group by start_date
                    order by start_date desc;
Run Code Online (Sandbox Code Playgroud)

joostschouten似乎已经找到了最优雅的解决方案(我自己还没有测试过)但下次我正在写一些要求它的东西我会记得测试它!

hep*_*olu 11

刚刚找到答案:如何在MySQL中使用数组循环?

set @billable_types = 'client1,client2,client3';
select * from mttl where find_in_set(mttl.type, @billable_types);
Run Code Online (Sandbox Code Playgroud)

  • "in"关键字不存在`错误代码:1064您的SQL语法中有错误; 检查与MySQL服务器版本对应的手册,以便在'@billable_types)附近使用正确的语法 (2认同)