使用ORDER BY选择COUNT混乱

时间:2014-06-18 12:04:12

标签: mysql

我有一个问题,我真的不明白。 查询

SELECT
    f.*,
    ftv.content,
    ftv.updated,
    COUNT(ftv.file_number) AS versions
FROM 
    files as f
INNER JOIN 
    files_text_versions AS ftv
ON 
    ftv.file_number = f.file_number
WHERE 
    f.file_number = '%s'
ORDER BY 
    ftv.updated DESC
LIMIT 1

完全忽略ORDER BY语句,但是如果我删除了

COUNT(ftv.file_number) AS versions

查询运行正常并按顺序排序。

为什么会这样,我该如何解决?

SQL摆弄同样的问题,但只有一个表:

http://sqlfiddle.com/#!2/c8f124/2

1 个答案:

答案 0 :(得分:3)

您的count(*)将查询转换为聚合查询。没有group by,它只返回一行。虽然在其他数据库中会出现错误,但MySQL允许使用此语法。

您可以通过添加group by来解决此问题。但是,您在ftv的其他两列中遇到问题。您可以通过巧妙的聚合获得所需的值:

SELECT f.*,
       substring_index(group_concat(ftv.content order by ftv.updated desc), ',', 1) as content,
       MAX(ftv.updated) as updated,
       COUNT(ftv.file_number) AS versions
FROM files f INNER JOIN 
     files_text_versions AS ftv
     ON ftv.file_number = f.file_number
WHERE f.file_number = '%s'
GROUP BY t.file_number
ORDER BY updated DESC
LIMIT 1;