我正在嘗試創建一條語句,該語句將返回按(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'
什麼? –