简体   繁体   English

计算具有相同 id 的行并打印

[英]count rows with same id and print

So I have this table 'users_photos'.所以我有这个表'users_photos'。 It contains 38k rows with user pictures.它包含 38k 行用户图片。 Every row contains id, userid and link to the photo.每行都包含 id、userid 和指向照片的链接。 So if a user have 3 pictures, that user id will show in 3 rows in the database.因此,如果用户有 3 张图片,则该用户 ID 将显示在数据库中的 3 行中。

What I want to do is count the number of users with 1 picture in the database, 2 pictures in the database etc.我想要做的是统计数据库中有1张图片,数据库中有2张图片等的用户数量。

UPDATE: I have now the following code更新:我现在有以下代码

$sql = $mysqli->query("SELECT count(*), count_users from (SELECT u_id, count(*) as count_users FROM users_photos group by u_id) temp group by count_users");
    $sql->data_seek(0);
while ($row = $sql->fetch_assoc()) {
    echo "".$fetch."  = " . $row['count_users'] . "\n<br>";
}

This prints the users that have 1 picture and up to 8. Not how many but only shows that in the database there is users that have 1 picture, 2 pictures etc. Now I need to figure out how to print the total users that have 1 picture etc.这将打印拥有 1 张图片和最多 8 张图片的用户。不是多少,而是仅显示数据库中有拥有 1 张图片、2 张图片等的用户。现在我需要弄清楚如何打印拥有 1 张图片的总用户图片等

Anyone have any tips?有人有任何提示吗? thanks on behalf!代表感谢!

使用此更新您的查询

$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");

Sql Query:查询:

$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");

You Can Print like this你可以这样打印


// After Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - count_users" . $row["count_users"]. "<br>";
    }
} else {
    echo "0 results";
}

You can do something like this:你可以这样做:

$con = mysqli_connect("localhost","my_user","my_password","my_db");
$sql = 'SELECT u_id, count(*) AS count_users FROM users_photos GROUP BY u_id';
$result = mysqli_query($con, $sql);
while ($row=mysqli_fetch_assoc($result)) {
    echo 'User id: ' . $row['u_id'] . ' Count: ' . $row['count_users'] . '<br>';
}

Keep in mind this is just a basic example.请记住,这只是一个基本示例。 In a real world application there is more to do such as checking for errors.在现实世界的应用程序中,还有更多工作要做,例如检查错误。

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

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