我写了一个复杂的查询,它最初检索了我想要的所有数据。现在我意识到我要求一个字段的值与我现在的值略有不同。
我有:IF(MIN(tasks.due_date) < NOW(),1,0) AS taskoverdue
我想拥有它:
IF(MIN(tasks.due_date WHERE tasks.completed != 1) < NOW(),1,0) AS taskoverdue
我知道这种语法不起作用,是否有任何人可以想到会实现这种结果的操作?
由于我的查询很复杂,我不能改变where子句或group by子句,并且我不能在select子句中运行子查询而不会大大地破坏我的应用程序的速度。哦,我正在使用PHP,但我正在寻找一个mysql解决方案。
以下是我的完整查询,仅用于踢:
SELECT
tickets.id,
tickets.user_id,
tickets.name,
COUNT(DISTINCT tasks.id) AS numTasks,
IF(MIN(tasks.due_date) < NOW(),1,0) AS taskoverdue,
IF(tickets.due_date < NOW(),1,0) AS ticketoverdue,
tasks.queue_id AS queue_id ,
IF(MIN(tasksteps.time_due) < NOW(),1,0) AS taskstepoverdue,
COUNT(DISTINCT ticketnotes.ticket_id) as notes
FROM
tickets
LEFT OUTER JOIN ticketsinqueues ON tickets.id = ticketsinqueues.ticket_id
LEFT OUTER JOIN tasks ON tickets.id = tasks.ticket_id
LEFT OUTER JOIN tasksteps ON tasks.id = tasksteps.task_id
LEFT OUTER JOIN ticketnotes ON tickets.id = ticketnotes.ticket_id
WHERE
ticketsinqueues.queue_id != tasks.queue_id AND
tickets.status = (var decided on run time)
GROUP BY
tickets.id,tasks.queue_id
UNION
SELECT
tickets.id,
tickets.user_id,
tickets.name,
COUNT(DISTINCT tasks.id) AS numTasks,
IF(MIN(tasks.due_date) < NOW(),1,0) AS taskoverdue,
IF(tickets.due_date < NOW(),1,0) AS ticketoverdue,
tasks.queue_id AS queue_id ,
IF(MIN(tasksteps.time_due) < NOW(),1,0) AS taskstepoverdue,
COUNT(DISTINCT ticketnotes.ticket_id) as notes
FROM
tickets
LEFT OUTER JOIN ticketsinqueues ON tickets.id = ticketsinqueues.ticket_id
LEFT OUTER JOIN tasks ON tickets.id = tasks.ticket_id
LEFT OUTER JOIN tasksteps ON tasks.id = tasksteps.task_id
LEFT OUTER JOIN ticketnotes ON tickets.id = ticketnotes.ticket_id
WHERE
ticketsinqueues.queue_id = tasks.queue_id AND
tickets.status = (var decided on run time)
GROUP BY
tickets.id,tasks.queue_id
UNION
SELECT
tickets.id,
tickets.user_id,
tickets.name,
0 AS numTasks,
0 AS taskoverdue,
IF(tickets.due_date < NOW(),1,0) AS ticketoverdue,
ticketsinqueues.queue_id AS queue_id ,
0 AS taskstepoverdue,
0 AS notes
FROM
tickets
LEFT OUTER JOIN ticketsinqueues ON tickets.id = ticketsinqueues.ticket_id
WHERE
tickets.status = (var decided on run time) AND
NOT EXISTS (
SELECT
*
FROM
tasks
WHERE
tickets.id = tasks.ticket_id AND
tickets.queue_id = tasks.queue_id
GROUP BY
tasks.ticket_id,
tasks.queue_id)
ORDER BY id desc
任何帮助将不胜感激。
答案 0 :(得分:2)
MAX(tasks.completed != 1 AND tasks.due_date < NOW()) AS taskoverdue