dsfew215211 2015-02-04 23:54
浏览 61
已采纳

Mysql Query不会回显所有结果! PHP

My code goes like this,

$sql = "SELECT Month(time) as Month, Year(time) as Year,
title, COUNT(*) AS total FROM posts GROUP BY Year, Month ORDER BY time DESC";

$stmt = $conn->query($sql);

if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_array()){
  echo "<div class=title>" . $row["title"]. "</div>";
}
}

it is supposed to output 4 titles,

Bellavisa
Mist Neting
Turkey is cool!
Cock of the Rock

but it only outputs

Bellavisa

Turkey is cool!

Cock of the Rock

Note that bellavisa and mist neting are in the same year and month, (setting up an archive list)

EDIT

Here is some of the table data

title "bellavisa" content "yadadada" time "timestamp ..." Author "author"   

title "mist nesting" content "yadadada" time "timestamp ..." Author "author"
  • 写回答

1条回答 默认 最新

  • dongse5528 2015-02-05 00:31
    关注

    Well, title is per post, so to get all the titles you should use no GROUP BY, while COUNT(*) is per month, so to get counts you need to GROUP BY the way you do, so in a simple SELECT you can either select one or another, but not both.

    To select both, you need to use a subquery, something along the lines of

    $sql = "SELECT Month(time) as Month, Year(time) as Year, title, (SELECT COUNT(*) FROM posts WHERE Month(time) = Month AND Year(time) = Year) AS total FROM posts ORDER BY time DESC;";
    

    Effectively, the query selects all the posts, and for each post computes a count. It is not the most efficient way to do that, you can rewrite it using a join, if every post has a unique ID. But for a table with reasonable size this query will work just fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?