gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:40:49 24 4
gpt4 key购买 nike

我正在尝试创建一个语句,该语句将返回按(username、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->执行(数组($_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 添加 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

尽管在这里您可以根据需要将它们排除在外。

要按totalsum 筛选结果,您可以执行以下操作:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com