我想使用GROUP BY
子句从表中选择一堆数据。这很好用,但我需要按照创建日期对数据进行排序,并使用ORDER BY
子句。我的问题是,我可以在同一个查询中使用这两个子句,还是应该在子查询中使用其中一个,还是其他什么?
原始查询(无修改)是:
SELECT *
FROM table
WHERE tag_draft=0
AND
(
(target_id=2 AND tag_del_target=0)
OR (source_id=2 AND tag_del_source=0)
)
AND updated IN
(
SELECT MAX(updated)
FROM table
GROUP BY thread_id
)
ORDER BY updated DESC
希望这个问题足够可读,以便能够回答它。
答案 0 :(得分:6)
MySQL SELECT语法是:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
所以,是的,你可以在同一个查询中使用GROUP BY和ORDER BY。什么不能正确排序结果是在子查询中使用ORDER BY。例如:
SELECT
something
FROM
aTable
JOIN
(SELECT myID FROM anotherTable ORDER BY myID) as bTable
ON aTable.ID=bTable.myID
首先订购子查询然后进行连接是没有任何意义的。