[英]mysql query count with out using group by, distinct or using php count
[英]mysql Count Distinct and get result using php
我有这样的 mysql 查询:
$topicreplycount = mysql_query('SELECT COUNT(DISTINCT post_msg_id) FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']);
并希望使用这样的方法得到结果:
$topicreplycount = mysql_result($topicreplycount);
所以假设表中有 4 个这样的 post_msg_id:
2956 2957 2957 2958
并且当前的 $row['post_msg_id'] 是 2958,有 3 个 post_msg_ids 比我比较的要少,只有 2 个不同的 post_msg_ids 因为其中两个是相同的,我希望“2”是回来
但它似乎不起作用,我这样做正确吗? 使用此方法,我根本没有在 $topicreplycount 变量中返回任何内容
我很确定 usign mysql_result($topicreplycount) 一定是错误的,但不知道该用什么代替
试试这个:
$sql = mysql_query('SELECT COUNT(DISTINCT post_msg_id) AS num_topics FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']);
$result = mysql_result($sql);
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['num_topics'];
使用mysql_result你需要至少指定行号
$topicreplycount = mysql_result($topicreplycount,0);
应该管用。 由于您使用了 COUNT() function,因此只会返回一个结果,这没问题。
但是,建议不要使用 mysql_ 系列函数。 它们实际上已被弃用(不是官方的,但即使是 PHP 文档也建议不要使用它们)。 你应该切换到 mysqli_ 或者,也许更好,PDO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.