Your above query works, except that when you GROUP BY
single column, you need to somehow merge all the others.
For example, GROUP BY Day
returns one record for each day. If several entries are entered during each day, and you request their id
, title
, category
, etc., How does MySQL know which of the several displays you, since it only shows you one row? (Usually it shows the "first" row for each day, as they appear in "SELECT * FROM mytable"
, but you should not rely on it).
The solution is that you somehow combine all of these individual properties, such as id
, into one line for each group. You can use GROUP_CONCAT
for this, as @narcisradu suggests.
SELECT GROUP_CONCAT(cms_news.news_id), GROUP_CONCAT(cms_news.news_title), DAYOFMONTH(FROM_UNIXTIME(cms_news.news_date)) as Day, GROUP_CONCAT(cms_news.news_category), GROUP_CONCAT(cms_news.news_source), GROUP_CONCAT(cms_news.news_type), GROUP_CONCAT(cms_news.news_content) FROM cms_news cms_news, GROUP BY DAYOFMONTH(FROM_UNIXTIME(cms_news.news_date)) ORDER BY cms_news.news_date DESC
This will give you, for example:
1,4 Story 1 Title, Story 2 Title <Day1> Funny,Sad ....
those. IDs, headings, categories, sources, types, and contents are converted to a single line, separated by commas, per day.
However, it seems that this does not quite meet your goals (having one line with the contents of all articles on this day seems pointless).
I think you should make your request:
SELECT cms_news.news_id, cms_news.news_title, DAYNAME(FROM_UNIXTIME(cms_news.news_date)) AS Day, cms_news.news_category, cms_news.news_source, cms_news.news_type, cms_news.news_content FROM cms_news cms_news, ORDER BY news_date DESC
(Note that I changed your DAYOFMONTH
to DAYOFWEEK
, because it seems to be better suited to your original question.)
The change is that there is no grouping - it is simply sorted by date.
Since your output is sorted by date, Day names will also be in order.
Then you can do something like this in your php:
$prevday=''; while($row = mysql_fetch_array($res)) { if ( $row['Day'] != $prevday ) { // day has changed! // make a new row. eg: echo "<br/> \n" . $row['Day']; } // now just list your article name echo " - " . $row['news_title']; $prevday = $row['Day']; }