我正在尝试创建一个语句,该语句将返回按(用户名、event_title 和 event_target
)分组并按该计数排序的 event_target
计数。
换句话说,totalsum
是(username、event_title 和 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->execute(array($_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->execute(array($_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
添加 or 条件?这可能是一个很糟糕的例子,但是假设有人搜索“6”,那么任何 totalsum
且值中包含 6 的结果也应该被返回。在一个完美的世界中,我希望能够做到:
OR `totalsum` LIKE 'searchquery'
最佳答案
您对 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
尽管在这里您可以根据需要将它们省略。
要按总和
过滤结果,您可以执行以下操作:
SELECT *, COUNT(`event_target`) `totalsum` FROM `testdb` WHERE `account_id` = ?
GROUP BY `username`, `event_title`, `event_target` HAVING `totalsum`=6
关于php - 在准备好的语句的 where 子句中使用计数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462318/