简体   繁体   English

在PHP / MySQL中按天分组记录

[英]Grouping records by day in PHP/MySQL

This is a common issue that I can't find an elegant way to handle. 这是一个常见的问题,我无法找到一种优雅的方式来处理。

Database contains 5000 records. 数据库包含5000条记录。 I need to show these records on a page, but they need to be sorted and grouped by day. 我需要在页面上显示这些记录,但是需要按天对它们进行排序和分组。

10/11/2009 10/11/2009

record3456 record3456

record456 record456

record456 record456

10/12/2009 10/12/2009

record345234 record345234

record3456 record3456

10/13/2009 2009年10月13日

10/14/2009 2009/10/14

record81 record81

record8324 record8324

record983 record983

record834 record834

10/15/2009 10/15/2009

record918 record918

... ...

etc. How can this be done in MySQL/PHP? 等等。如何在MySQL / PHP中完成? What about Ruby? 露比呢 I can grab all records and then sort them and manipulate them manually with PHP but that's SLOW. 我可以获取所有记录,然后对它们进行排序,并使用PHP对其进行手动操作,但这很慢。

Do a: 做一个:

ORDER BY your_date_column

in the query. 在查询中。 You'll probably have to do the grouping in PHP - just see if the data differs from the last row, if it does, print a header. 您可能必须在PHP中进行分组-仅查看数据是否与最后一行不同,如果有,则打印标题。

Assuming the example for 10/11/2009 is incorrect because of the duplicates, this is a standard pivot query. 假设由于重复而导致2009年10月10/11/2009的示例不正确,这是标准的数据透视查询。 It's called pivotting because you're wanting to change row to column data. 之所以称为透视,是因为您想将行数据更改为列数据。

SELECT CASE WHEN x.df = '10/11/2009' THEN x.record_column ELSE NULL END '10/11/2009',
       CASE WHEN x.df = '10/12/2009' THEN x.record_column ELSE NULL END '10/12/2009',
       CASE WHEN x.df = '10/13/2009' THEN x.record_column ELSE NULL END '10/13/2009',
  FROM (SELECT t.date_column,
               DATE_FORMAT(t.date_column, '%m/%d/%Y') 'df'
               t.record_column
          FROM TABLE t
      GROUP BY t.date_column,t.record_column) x

The problem with this is that your resultset will look like: 问题在于您的结果集将如下所示:

10/11/2009  | 10/12/2009    | 10/13/2009
-----------------------------------------
record3456  | NULL          | NULL
record456   | NULL          | NULL
NULL        | record345234  | NULL
NULL        | record3456    | NULL

It might be more simple & direct to just use: 使用起来可能更简单直接:

SELECT t.record_column '10/11/2009'
  FROM TABLE t
 WHERE t.date_column = '10/11/2009'

...to query the records you want, in separate queries. ...在单独的查询中查询所需的记录。

SELECT * 选择 *

FROM TABLE GROUP BY DAY(dateField) 从TABLE GROUP BY DAY(dateField)

ORDER BY DAY(dateField) ORDER BY DAY(dateField)

http://www.tizag.com/sqlTutorial/sqldate.php http://www.tizag.com/sqlTutorial/sqldate.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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