我正在尝试做这样的事情:
SELECT days.date, SUM(tes.duration) FROM (
SELECT
DATE_FORMAT(
now() - INTERVAL (@num := @num + 1) DAY,
'%Y-%m-%d'
) date
FROM time_entries, (SELECT @num:=-1) num
LIMIT 31
) AS days
LEFT JOIN (
SELECT te.duration, DATE_FORMAT(te.date, '%Y-%m-%d') date
FROM time_entries AS te
WHERE te.account_id = 50150 AND te.deleted_at IS NULL
) AS tes ON tes.date = days.date
GROUP BY days.date
ORDER BY days.date
但这似乎不可能在ecto。我正在尝试这个:
from(
# creates 30 rows for each date 30 days into the past
days in subquery(
from(
num in "time_entries, (SELECT @num := -1)",
select: %{
date: fragment("DATE_FORMAT(NOW() - INTERVAL (@num := @num + 1) DAY, '%Y-%m-%d')")
}
)
),
# join each date with time entries on this account and sub duration for each day
left_join: tes in subquery(
from(
# using time_entries__undeleted was really slow for some reason… need to look into that
te in "time_entries",
select: %{
duration: te.duration,
date: fragment("DATE_FORMAT(?, '%Y-%m-%d')", te.date),
where: te.account_id == ^user.account_id
},
)
), on: tes.date == days.date,
group_by: days.date,
order_by: days.date
)
但我得到错误:
(Mariaex.Error) (1146): Table 'development.time_entries, (select @num := -1)' doesn't exist
我需要在此查询之上动态撰写,因此我不想诉诸Ecto.Adapters.SQL.query!
。有什么想法吗?
答案 0 :(得分:2)
你不能这样做,但语法SELECT … FROM a, b …
大致等同于Ecto支持的SELECT … FROM a CROSS JOIN b …
。所以你需要的是
from entry in "time_entries",
cross_join: num in fragment("(SELECT @num = -1)"),
…