时间:2021-07-01 10:21:17 帮助过:198人阅读
首先,这是不可能实现的
mysql的查询的顺序
select -> from-> where->group by->having->order by.
但mysql的解析器执行顺序:
from-> where->group by->having->select->order by.
所以,从执行的流程来看,是先group by 然后在 order by.
order by拿到的结果里已经是group by以后的结果.
因此,order by的字段必须是group by 里面已经存在的字段.
如果有人问到,想group by同时,进行排序
注意,查询 按照索引进行排序
用 group_concat进行排序
SELECT
pq.id,SUBSTRING_INDEX( group_concat( pq.paperId ORDER BY pq.id),‘,‘,1
) AS paperId,SUBSTRING_INDEX(group_concat( pq.questionType ORDER BY pq.id),‘,‘,
1
) AS questionType,pq.questionId,p.id as pId,p.type,
SUBSTRING_INDEX( group_concat( p.type ORDER BY pq.id),‘,‘,1
) AS pType
FROM
paper_question as `pq` left join `question` as `p` on `pq`.`questionId` = `p`.`id`
WHERE
pq.paperId = 470 GROUP BY pq.paperId;
mysql 用 group by 和 order by同时使用
标签:HERE bst order join substr having group by index substring