2015-06-14 64 views
0

我一直在試圖弄清楚如何修改此查詢,以便結果集不包含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 
+0

在你選中剛纔設置'選擇 newel_inventoryKeywordIdDictionaryId.inventoryId'沒有'numHits' –

回答

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; 
+0

謝謝。完美的感覺! – kambythet

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; 
+0

謝謝。我選擇了Salman A的答案,因爲它是在您之前提交的,但您的作品也是如此。 – kambythet

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;