我正在尝试创建一个语句,该语句将返回按{({1}}分组)并按该计数排序的event_target
计数。
换句话说,username, event_title, and event_target
是(totalsum
)所有相同值的行数。
问题是在DESC中没有按总数排序结果。
username, event_title, and event_target
$ stmt->执行(阵列($ _ SESSION ['用户'] [' ACCOUNT_ID']));
$stmt = $db->prepare("SELECT *, COUNT(`event_target`) 'totalsum' FROM `testdb` WHERE `account_id` = ? GROUP BY `username`, `event_title`, `event_target` ORDER BY 'totalsum' DESC");
其次,我还想在我的WHERE子句中使用$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//print out the array echo '<pre>',print_r($results,true),'</pre>';
值...所以说我只想返回值,其中totalsum = 6.这将返回一个空数组。如果我在没有此WHERE子句的情况下使用上述语句,则会有totalsum = 6的结果。
totalsum
$ stmt-&GT;执行(阵列($ _ SESSION [&#39;用户&#39;] [&#39; ACCOUNT_ID&#39;]));
$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");
我在这里做错了什么?
修改
感谢您对此的澄清!这对我来说似乎最适合。
$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
添加或条件?这可能是一个很糟糕的例子,但有人说要搜索“#6;&#39;然后,还应返回值为totalsum
且值为6的任何结果。在一个完美的世界里,我希望能够做到:
totalsum
答案 0 :(得分:2)
您对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
答案 1 :(得分:2)
试试这个:
SELECT
*,
COUNT(`event_target`) 'totalsum'
FROM
`testdb`
WHERE
`account_id` = ?
GROUP BY
`username`,
`event_title`,
`event_target`
HAVING
COUNT(`event_target`) = 6
ORDER BY
'totalsum' DESC