简体   繁体   中英

MySQL Order By Date

I have an a MySQL database. My database contains documents with a datetime column called "created". I want to group by day in order to have the document count per day. However, some days have zero documents and as a result they are not part of the output. For example I need '2001-01-01' to have a zero count if documents do not exist.

I am thinking of creating an extra table with the date range I am interested on and the to Do an outer join with my table. Then I can group by date to have my results.

Is there any better way of doing such a thing?

My SQL code:

Select date(created_at),c.text from Dates d left outer join classifier c on d.n=DATE(c.created_at)
    where c.classifier="2014streamlrall"
    and date(c.created_at)>='2014-03-01' and date(c.created_at)<='2014-05-01'
order by d.n;

The left join still does not work.

There is no better way for that in MySQL .

It lacks both a method to generate an arbitrary length resultset (similar to PostgreSQL's generate_series ) and recursive SQL required to emulate such a method (which is used in SQL Server and Oracle).

Even on SQL Server, populating and keeping a table with 100 years worth of dates (which takes but a little more than 73K records) gives much better performance on reports similar to yours than using a generated resultset.

Is your real issue with having a create a row with '2001-01-01: 0'? If so, just wrap the MySQL with PHP and control your output with PHP. Then you just echo (or create an XML entry, whatever formatting you need) with the date and the result, even if it's 0. Even if you're currently know nothing about PHP, there are plenty of tutorials on how to run MySQL queries in PHP and output results. Good luck.

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