简体   繁体   English

mysql Count Distinct 并使用 php 得到结果

[英]mysql Count Distinct and get result using php

I have a mysql query like this:我有这样的 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']);

and hope to get the result using something like this:并希望使用这样的方法得到结果:

$topicreplycount = mysql_result($topicreplycount);

so lets say there are 4 post_msg_ids like this in the table:所以假设表中有 4 个这样的 post_msg_id:

2956 2957 2957 2958 2956 2957 2957 2958

and the current $row['post_msg_id'] is 2958, there are 3 post_msg_ids that are less than the one I am comparing it to, and only 2 Distinct post_msg_ids since two of them are the same, I am expecting "2" to be returned并且当前的 $row['post_msg_id'] 是 2958,有 3 个 post_msg_ids 比我比较的要少,只有 2 个不同的 post_msg_ids 因为其中两个是相同的,我希望“2”是回来

but it doesn't seem to work, am I doing this correctly?但它似乎不起作用,我这样做正确吗? I am not getting anything returned in the $topicreplycount variable at all using this method使用此方法,我根本没有在 $topicreplycount 变量中返回任何内容

I am pretty sure usign mysql_result($topicreplycount) must be wrong but don't know what to use instead我很确定 usign mysql_result($topicreplycount) 一定是错误的,但不知道该用什么代替

Try this:试试这个:

$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'];

Using mysql_result you need to specify at least the row number so使用mysql_result你需要至少指定行号

$topicreplycount = mysql_result($topicreplycount,0);

should work.应该管用。 As there will only ever be one result returned because you used the COUNT() function this will be fine.由于您使用了 COUNT() function,因此只会返回一个结果,这没问题。

However, it is recommended NOT to use the mysql_ family of functions.但是,建议不要使用 mysql_ 系列函数。 They are effectively deprecated (not officially but even the PHP docs recommends not to use them).它们实际上已被弃用(不是官方的,但即使是 PHP 文档也建议不要使用它们)。 You should switch to mysqli_ or, perhaps better still, PDO.你应该切换到 mysqli_ 或者,也许更好,PDO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM