按列分组和排序但不包括结果中的该列

时间:2015-06-14 19:29:02

标签: mysql sql group-by sql-order-by

我一直试图找出如何修改此查询,以便结果集不包含numHits。我想以相同的顺序获得相同的结果,只是没有包含numHits。

SELECT 
    `newel_inventoryKeywordIdDictionaryId`.`inventoryId`
    ,COUNT(`newel_inventoryKeywordIdDictionaryId`.`inventoryId`) as numHits 
FROM 
    `newel_inventoryKeywordIdDictionaryId`
    , `newel_inventoryDictionary`
WHERE 
    `newel_inventoryKeywordIdDictionaryId`.`dicId` = `newel_inventoryDictionary`.`dicId` 
    AND ( 
        `newel_inventoryDictionary`.`word` = 'alabaster' OR `newel_inventoryDictionary`.`word` = 'chess'
    ) 
GROUP BY inventoryId 
ORDER BY numHits DESC;

样本结果:

inventoryId, numHits
6928, 2
6929, 2
6924, 2
6925, 2
13772, 2
6926, 2
18203, 1
6931, 1
13863, 1
18402, 1

期望的结果:

inventoryId
6928
6929
6924
6925
13772
6926
18203
6931
13863
18402

3 个答案:

答案 0 :(得分:1)

将列从SELECT子句移动到ORDER BY子句:

SELECT 
    `newel_inventoryKeywordIdDictionaryId`.`inventoryId`
FROM 
    `newel_inventoryKeywordIdDictionaryId`
    , `newel_inventoryDictionary`
WHERE 
    `newel_inventoryKeywordIdDictionaryId`.`dicId` = `newel_inventoryDictionary`.`dicId` 
    AND ( 
        `newel_inventoryDictionary`.`word` = 'alabaster' OR `newel_inventoryDictionary`.`word` = 'chess'
    ) 
GROUP BY inventoryId 
ORDER BY COUNT(`newel_inventoryKeywordIdDictionaryId`.`inventoryId`) DESC;

答案 1 :(得分:0)

SELECT 
`newel_inventoryKeywordIdDictionaryId`.`inventoryId`
FROM 
`newel_inventoryKeywordIdDictionaryId`
, `newel_inventoryDictionary`
WHERE 
`newel_inventoryKeywordIdDictionaryId`.`dicId` = `newel_inventoryDictionary`.`dicId` 
AND ( 
    `newel_inventoryDictionary`.`word` = 'alabaster' OR `newel_inventoryDictionary`.`word` = 'chess'
) 
GROUP BY inventoryId 
ORDER BY COUNT(`newel_inventoryKeywordIdDictionaryId`.`inventoryId`) DESC;

答案 2 :(得分:0)

您只需将聚合放在ORDER BY中即可。但是,您还应该:

  • 使用显式join语法。 从不from子句中使用逗号。
  • 使用表别名。它们使查询更容易编写和阅读。
  • 使用in代替一堆or语句。

以下是查询的改进版本:

SELECT kdi.inventoryId
FROM newel_inventoryKeywordIdDictionaryId kdi JOIN
     newel_inventoryDictionary id
     ON kdi.dicId = id.dictId
WHERE id.word IN ('alabaster', 'chess') 
GROUP BY kdi.inventoryId 
ORDER BY COUNT(*) DESC;