【发布时间】:2014-05-04 22:31:07
【问题描述】:
我正在尝试创建一个语句,该语句将返回按 (username, event_title, and event_target) 分组并按该计数排序的 event_target 计数。
换句话说,totalsum 是 (username, event_title, and event_target) 都是相同值的行数。
问题是结果在 DESC 中没有按总计排序。
$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['user']['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['user']['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”,那么任何带有 totalsum 且值中包含 6 的结果也应该返回。在一个完美的世界里,我希望能够做到:
OR `totalsum` LIKE 'searchquery'
【问题讨论】:
-
HAVING 子句怎么样?