简体   繁体   中英

PHP MYSQLI - Selecting multiple rows grouped by month

I have a series of news articles, that are stored inside a database, like so:

id
articleTitle
articleBody
articleBy
category
dateEntered

What I want to do is select all of the articles and group them by a particular month / year that they were entered. For example:

  • May
    • News article 1
    • News article 2
    • News article 3
  • Feb
    • News article 4
    • News article 5
    • News article 6

I am able to select the months, as well as how many items are there, using the following:

 SELECT id, articleTitle, YEAR(dateEntered) AS 'year', MONTH(dateEntered) AS 'month'  FROM News GROUP BY YEAR(dateEntered), MONTH(dateEntered) DESC

Whenever I try to output the contents of 'articleTitle' it only shows 1 result, when there should be 28 entries that are showing.

Where am I going wrong in my query?

The GROUP BY clause collapses sets of rows with common values for the expressions in the GROUP BY clause. With this in your query:

GROUP BY YEAR(dateEntered), MONTH(dateEntered)

The query will only return a single row for distinct values of those expressions. There is nothing wrong with doing this. This is convenient if you want to return a count of the number of rows that have that year and month, for example

  SELECT DATE_FORMAT(dateEntered,'%Y-%m')
       , COUNT(1) AS cnt_
    FROM mytable 
   GROUP BY DATE_FORMAT(dateEntered,'%Y-%m')

If you don't want your query to "collapse" the rows, then don't use a GROUP BY clause.


I suspect you want to use an ORDER BY clause, not a GROUP BY . To make the order the rows are returned in more deterministic, you can add more expressions to the ORDER BY clause. Also note that ASC and DESC apply to each expression in the ORDER BY clause.

For example:

SELECT n.id
     , n.articleTitle
     , YEAR(n.dateEntered)  AS `year`
     , MONTH(n.dateEntered) AS 'month'
  FROM News n 
 ORDER
    BY YEAR(n.dateEntered)  DESC
     , MONTH(n.dateEntered) DESC
     , n.id                 DESC

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