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

时间:2017-10-05 17:15:20

标签: php mysql

所以我有这张桌子' users_photos'。它包含38k行和用户图片。每行包含id,userid和照片的链接。因此,如果用户有3张图片,那么该用户ID将在数据库中显示3行。

我想要做的是计算数据库中1张图片的用户数量,数据库中的2张图片等。

更新:我现在有以下代码

$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>";
}

这会打印出包含1张图片且最多8张的用户。不会显示多少但仅显示数据库中有1张图片,2张图片等的用户。现在我需要弄清楚如何打印总用户有1张图片等

任何人有任何提示吗?谢谢代表!

3 个答案:

答案 0 :(得分:0)

使用此更新您的查询

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

答案 1 :(得分:0)

Sql Query:

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

你可以这样打印

// 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";
}

答案 2 :(得分:0)

您可以这样做:

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

请记住,这只是一个基本的例子。在现实世界的应用程序中,还有更多工作要做,例如检查错误。