php - 在准备好的语句的 where 子句中使用计数值

标签 php mysql sql pdo

我正在尝试创建一个语句,该语句将返回按(用户名、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/

相关文章:

mysql - 使用 JOIN 过滤数据

php - 使用 Laravel 和 Carbon 将用户提供的 1970 年之前的日期插入到 MySql

sql - 如果 Column1 不为空,则按 Column1 排序,否则按 Column2 排序

mysql - 如何使用 sql 查询检查标志值的第五位是 0 还是 1?

PHP 嵌套 for 循环

php - 包含一个 SVG 文件并改变它的高度

mysql - 在 mySQL 数据库中选择一个复选框

Python SQL 从特定变量字段中选择行

javascript - 如何在页面加载之前显示 reCAPTCHA

php - 如何使用 Phalcon 框架加入 2 个集合?