2014-05-04 26 views
2

我正在嘗試創建一條語句,該語句將返回按(username, event_title, and event_target)分組的計數event_target並按該計數排序。在準備好的語句的where子句中使用計數值

換句話說,totalsum是其中(username, event_title, and event_target)都是相同的值的行數。

問題是結果沒有在DESC中按totalals排序。

$stmt = $db->prepare("SELECT *, COUNT(`event_target`) 'totalsum' FROM `testdb` WHERE `account_id` = ? GROUP BY `username`, `event_title`, `event_target` ORDER BY 'totalsum' DESC"); 

$ stmt->執行(陣列($ _ SESSION [ '用戶'] [ 'ACCOUNT_ID']));

$results = $stmt->fetchAll(PDO::FETCH_ASSOC); 

//print out the array echo '<pre>',print_r($results,true),'</pre>'; 



其次,我也想在我的WHERE子句中使用totalsum值...所以說,我只想要返回值,其中totalsum = 6,這將返回一個空數組。如果我在沒有這個WHERE子句的情況下使用上面的語句,那麼結果總數爲6。

$stmt = $db->prepare("SELECT *, COUNT(`event_target`) 'totalsum' FROM `testdb` WHERE `account_id` = ? AND 'totalsum' = 6 GROUP BY `username`, `event_title`, `event_target` ORDER BY 'totalsum' DESC"); 

$ stmt->執行(陣列($ _ SESSION [ '用戶'] [ 'ACCOUNT_ID']));

$results = $stmt->fetchAll(PDO::FETCH_ASSOC); 

//print out the array echo '<pre>',print_r($results,true),'</pre>'; 



我在做什麼錯在這裏?

編輯:

謝謝你的澄清這個!目前這似乎對我最有效。

SELECT *, COUNT(`event_target`) `totalsum` FROM `testdb` WHERE `account_id` = ? 
    GROUP BY `username`, `event_title`, `event_target` HAVING `totalsum`=6 

我遇到了另一個問題。我詢問totalsum的條件的原因是這是對搜索功能的修改。所以......典型的搜索查詢可能是這樣的:

SELECT *, COUNT(`event_target`) `totalsum` FROM `testdb` WHERE `account_id` = ? 
    AND (`event_target` LIKE 'searchquery' OR `event_title` LIKE 'searchquery' OR `event_name` LIKE 'searchquery') 
    GROUP BY `username`, `event_title`, `event_target` ORDER BY `totalsum` DESC 

我如何在一個或條件添加爲totalsum?這可能是一個不好的例子,但是如果有人搜索'6',那麼返回值爲6的totalsum的任何結果都應該返回。在一個完美的世界,我希望能夠做到:

OR `totalsum` LIKE 'searchquery' 
+0

什麼? –

回答

2

您使用的是一種錯誤的報價爲totalsum

SELECT *, COUNT(`event_target`) 'totalsum' FROM `testdb` WHERE `account_id` = ? GROUP BY `username`, `event_title`, `event_target` ORDER BY 'totalsum' DESC 

應該是:

SELECT *, COUNT(`event_target`) `totalsum` FROM `testdb` WHERE `account_id` = ? GROUP BY `username`, `event_title`, `event_target` ORDER BY `totalsum` DESC 

雖然這裏如果你願意,你可以將它們排除在外。

要通過totalsum過濾結果,你可以這樣做:

SELECT *, COUNT(`event_target`) `totalsum` FROM `testdb` WHERE `account_id` = ? 
    GROUP BY `username`, `event_title`, `event_target` HAVING `totalsum`=6 
2

試試這個:

約HAVING子句
SELECT 
    *, 
    COUNT(`event_target`) 'totalsum' 
FROM 
    `testdb` 
WHERE 
    `account_id` = ? 
GROUP BY 
    `username`, 
    `event_title`, 
    `event_target` 
HAVING 
    COUNT(`event_target`) = 6 
ORDER BY 
    'totalsum' DESC 
+0

學到了新東西...會像'HAVING COUNT('event_target')像somevalue'一樣工作? – user756659

+0

哼,你在比較一個使用LIKE的INT, 你最好使用'HAVING COUNT(event_target)BETWEEN 5 AND 7' –