简体   繁体   中英

How to fetch 5 most recent values and number of count in a column SQL

According to the table, I have to count the top 3 most frequent bookID and the count of the bookID.

桌子

I have figured out how to get the top 3, however I couldn't figured how to display the number of count in the bracket after the comma.

I have to put these into the brackets separate by commas, it look like this:

[top1 bookid , the number of count] => [17,6]
[top2 bookid , the number of count] => [13,6]
[top3 bookid , the number of count] => [16,5]
$query ="SELECT bookID FROM issue_books GROUP BY bookID ORDER BY COUNT(*) DESC LIMIT 3 ";

$query_run = mysqli_query($connection,$query);

  foreach ($query_run as $row)
  { 
    echo '['". $row['bookID'];.",".xxxxx."']';
  }

Is there any way to display the count of the frequency number together?

Add the count to the select clause?

$query = "SELECT bookID, COUNT(*) AS cnt FROM issue_books GROUP BY bookID ORDER BY cnt DESC LIMIT 3 ";
$query_run = mysqli_query($connection, $query);
foreach ($query_run as $row) {
    echo "[" . $row['bookID'] . ", " . $row['cnt'] . "]\n";
}

You could add the count(*) to the select list:

$query =
"SELECT bookID, COUNT(*) AS cnt FROM issue_books GROUP BY bookID ORDER BY COUNT(*) DESC LIMIT 3 ";

$query_run = mysqli_query($connection,$query);

foreach ($query_run as $row)
{ 
    echo '[' . $row['bookID']; . ',' . $row['cnt'] . ']';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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