在GROUP BY之前的MySQL Order结果

时间:2017-02-13 20:46:37

标签: mysql

您好我想知道如何在以下QUERY上执行ORDER BY:

SELECT t.*, td.id, td.taskname, td.status, td.date, td.priority,
        DATE_FORMAT(td.completed_on,'%d %b %Y') as completed_on,
        td.completed_by, td.id as idmain,  m.name, c.name as compname,
        GROUP_CONCAT(s.name SEPARATOR '   ') as names
FROM task_assigns t
    LEFT JOIN tasks_todo td ON t.taskid = td.id 
    LEFT JOIN members m ON t.userid = m.id
    LEFT JOIN members s ON t.task_assign = s.id
    LEFT JOIN members c ON td.completed_by = c.id           
WHERE (   t.task_assign = '$userid_task' 
       OR t.userid = '$userid_task' ) 
AND t.date  < NOW() - INTERVAL 10 DAY 
AND td.status = 0  
GROUP BY t.taskid 
LIMIT 10

现在返回的结果是按随机顺序我希望返回它们总是按 id ACS taskid

的顺序排序

enter image description here

2 个答案:

答案 0 :(得分:1)

只需在ORDER BY子句中添加两列。

此外,只有在禁用ONLY_FULL_GROUP_BY并且可能产生意外结果时,此类分组才有效。

select t.*,
    td.id,
    td.taskname,
    td.status,
    td.date,
    td.priority,
    DATE_FORMAT(td.completed_on, '%d %b %Y') as completed_on,
    td.completed_by,
    td.id as idmain,
    m.name,
    c.name as compname,
    GROUP_CONCAT(s.name SEPARATOR '&nbsp;&nbsp; ') as names
from task_assigns t
left join tasks_todo td on t.taskid = td.id
left join members m on t.userid = m.id
left join members s on t.task_assign = s.id
left join members c on td.completed_by = c.id
where (
        t.task_assign = '$userid_task'
        or t.userid = '$userid_task'
        )
    and t.date < NOW() - INTERVAL 10 DAY
    and td.status = 0
group by t.taskid
order by t.id,
    t.taskid LIMIT 10

答案 1 :(得分:1)

语法的顺序是

GROUP BY t.taskid 
ORDER BY t.taskid, other_column_if_you_like
LIMIT 10