获取最高值的数组查询mysql,php

时间:2015-02-11 14:50:12

标签: php mysql arrays wordpress count

非常感谢其他人,我现在得到这个查询。它的工作正常,但我需要得到post_id(how_many)的最高值。似乎无法在其上设置MAX(count(*))。所以我怎么能改变这个以获得每个id的最高计数?我只需要count ==最高的每个id的值。我怎么能这样做?谢谢你的帮助。

$test = $wpdb->get_results('select 
    posts_id, value,count(*) as how_many
From wp_mrp_rating_item_entry_value
group by
    posts_id, value
order by count(*) desc');
echo '<pre>';
print_r($test);
echo '</pre>';

我需要按MAX((count(*))或MAX((count(how_many))

的顺序排序

我已经读过这篇文章,但我不知道如何将其用于我的目的Filtering log file using COUNT, GROUP BY, ORDER BY MAX

这是我现在得到的输出的一个例子。所以不应出现数字1,因为数字[0]已被投票2次。 (多少)。我只需要输出中的每个id 1x。没有id应该出现两次或更多次。因为只需要最高计数。谢谢,对不起英语不好。

Array
(
    [0] => stdClass Object
        (
            [posts_id] => 336
            [value] => 8
            [how_many] => 2
        )

    [1] => stdClass Object
        (
            [posts_id] => 336
            [value] => 7
            [how_many] => 1
        )

    [2] => stdClass Object
        (
            [posts_id] => 380
            [value] => 5
            [how_many] => 1
        )

    [3] => stdClass Object
        (
            [posts_id] => 378
            [value] => 7
            [how_many] => 1
        )

    [4] => stdClass Object
        (
            [posts_id] => 329
            [value] => 2
            [how_many] => 1
        )

    [5] => stdClass Object
        (
            [posts_id] => 327
            [value] => 3
            [how_many] => 1
        )

)

1 个答案:

答案 0 :(得分:0)

您可以根据针对最大计数的子查询匹配来过滤HAVING子句中的结果组:

SELECT   posts_id, value, COUNT(*) AS how_many
FROM     wp_mrp_rating_item_entry_value t1
GROUP BY posts_id, value
HAVING   how_many = (
           SELECT   COUNT(*)
           FROM     wp_mrp_rating_item_entry_value t2
           WHERE    t2.posts_id = t1.posts_id
           GROUP BY t2.value
           ORDER BY COUNT(*) DESC
           LIMIT    1
         )