我没想到会发现这么困难,但我试图在MySQL中设置一个用户变量来包含一个值数组。我不知道如何做到这一点所以尝试做一些研究,并且很惊讶找不到答案。我试过了:
SET @billable_types = ['client1','client2','client3'];
原因是我想稍后在以下语句中使用该变量:
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;
非常感谢您的帮助。
快进一段时间,我最终得到了以下快速而肮脏的解决方案,这并没有给我在代码中其他地方重新使用数组的灵活性,但是嘿,这是一个不可完成的管理任务,所以我不想花更多的时间在上面。
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;
joostschouten似乎已经找到了最优雅的解决方案(我自己还没有测试过)但是下次我正在写一些要求它的东西我会记得测试它!
答案 0 :(得分:11)
刚刚在这里找到答案:How to cycle with an array in MySQL?
set @billable_types = 'client1,client2,client3';
select * from mttl where find_in_set(mttl.type, @billable_types);
答案 1 :(得分:0)
正如Marc B所提到的,MYSQL中没有数组变量。
find_in_set 解决方案的替代方法是使用 SELECT 和 UNION 来模拟数组:
SELECT billable_type FROM (
SELECT 'client1' AS billable_type UNION
SELECT 'client2' AS billable_type UNION
SELECT 'client3' AS billable_type) AS t
所以你的查询看起来像这样:
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 (
SELECT billable_type FROM (
SELECT 'client1' AS billable_type UNION
SELECT 'client2' AS billable_type UNION
SELECT 'client3' AS billable_type) AS t
)
and tlg.task_id = mttl.id
group by start_date
order by start_date desc;
答案 2 :(得分:0)
如果用户具有CREATE TABLE权限,则可以通过创建临时单列表来模拟数组。可以使用SELECT语句检索表中的一个或多个值。临时表在会话结束时被删除,但是在不再需要它们时明确删除它们是个好主意。
CREATE TEMPORARY TABLE billable_types (c VARCHAR(16));
INSERT INTO billable_types VALUES ('client1'), ('client2'), ('client3');
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 (SELECT * FROM billable_types)
and tlg.task_id = mttl.id
group by start_date
order by start_date desc;
DROP TABLE billable_types;