MySQL语法问题与工作查询相结合

时间:2015-01-29 21:35:06

标签: mysql sql syntax

我刚刚开始学习SQL,并设法拼凑了几个有效的查询,但是当我将它们组合起来时,我收到了语法错误。抛出错误的查询:

SELECT sca_ticket_status.name As Status, AVG(QueueTime) 
FROM (SELECT DateDiff (created, now()) as 'QueueTime'
FROM sca_ticket as SubQuery 
LEFT JOIN sca_ticket_status
ON sca_ticket.status_id = sca_ticket_status.id
GROUP BY name
ORDER BY sort

作为参考,我试图利用的两个工作查询如下:

SELECT sca_ticket_status.name As Status, COUNT(sca_ticket.ticket_id) AS Count 
FROM sca_ticket
LEFT JOIN sca_ticket_status
ON sca_ticket.status_id = sca_ticket_status.id
WHERE sca_ticket.created between date_sub(now(),INTERVAL 1 WEEK) and now()
GROUP BY name
ORDER BY sort

SELECT AVG(QueueTime)
FROM (SELECT DateDiff (created, now()) as 'QueueTime'
FROM `sca_ticket`
WHERE `status_id` = 1) as SubQuery  

2 个答案:

答案 0 :(得分:1)

尝试关闭第二个选择语句

SELECT sca_ticket_status.name As Status, AVG(QueueTime) 
FROM (SELECT status_id, DateDiff (created, now()) as 'QueueTime'
FROM sca_ticket) q1
LEFT JOIN sca_ticket_status
ON q1.status_id = sca_ticket_status.id
GROUP BY name
ORDER BY sort

如果您想稍后加入,请在内部选择列表中公开status_id列。

答案 1 :(得分:0)

您根本不需要子查询。这只会减慢MySQL中的处理速度(优化器不是很聪明;它实现了丢失索引信息的子查询)。

SELECT ts.name As Status, AVG(DateDiff(t.created, now())) 
FROM sca_ticket t LEFT JOIN
     sca_ticket_status ts
     ON t.status_id = ts.id
GROUP BY ts.name
ORDER BY sort