简体   繁体   English

如何在php mysql中找不到具有相同值的行

[英]How to find no of rows with same value in php mysql

I have one table with event_id & image_id. 我有一张带有event_id和image_id的表。 I want to find the no of rows which with the same value -> max in this table. 我想在此表中找到具有相同值-> max的行数。

means in this table output should like: 1508706279 -> image_id 4 -> no of rows 表示此表中的输出应为:1508706279-> image_id 4->行数

here is my table. 这是我的桌子。

在此处输入图片说明

below is the code which i have tried. 下面是我尝试过的代码。

$sql2 = "select image_id, COUNT(*) as count from user_likes where event_id  = '$id' GROUP BY image_id";

                    if($result2 = mysqli_query($conn, $sql2)) {

                        $result1 = mysqli_fetch_array($result2);

                        $win = $result1['image_id'];
                        $count = $result1['count'];

                    } 

Now, i can't understand what is issue but this code works fine when there are rows between id 52 to 60 it shows output: 现在,我不明白是什么问题,但是当id在52到60之间的行显示输出时,此代码可以正常工作:

1508706279 -> image_id 4 -> no of rows 1508706279-> image_id 4->行数

but when i add two more rows with id 64 & 65 it shows output: 但是当我再添加两行ID为64和65的行时,它会显示输出:

818525590 -> image_id 1 -> no of rows 818525590-> image_id 1->行数

help me in this what mistake i am doing here.!! 帮助我解决我在这里犯的错误!!

Your query return a collection of image_id and count. 您的查询返回image_id和count的集合。 The collection is not ordered so you have the first one from select if you need the max try ordering by count(*) desc 集合没有排序,因此如果需要按count(*)desc进行最大尝试排序,则可以选择第一个集合

  $sql2 = "select image_id, COUNT(*) as count 
            from user_likes 
            where event_id  = '$id' 
            GROUP BY image_id
            ORDER BY count(*) DESC";

and you can limit to 1 if you need one row only 如果只需要一行,则可以限制为1

  $sql2 = "select image_id, COUNT(*) as count 
            from user_likes 
            where event_id  = '$id' 
            GROUP BY image_id
            ORDER BY count(*) DESC LIMIT 1";

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

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