[英]How to group output rows based on date either on mySQL or PHP?
The following query returns some rows, that each one has its own date_created
. 以下查询返回一些行,每个行都有自己的
date_created
。
SELECT *
FROM table1 l
inner join table2 d
ON d.id = l.id
WHERE l.company_id = 1
UNION ALL
SELECT *
FROM table1 l
inner join table3 p
ON p.id = l.id
WHERE p.company_id = 1
sample output: 样本输出:
company_id ---- user_id ---- text ---- dateAndTime
1 ---- abc ---- hi ---- 2017-08-17 22:26:18
1 ---- def ---- hey ---- 2017-08-08 11:57:26
1 ---- abc ---- hi ---- 2017-08-08 11:55:40
1 ---- ghz ---- sup ---- 2017-07-25 16:01:34
What I want to achieve: 我要实现的目标:
I am running a php foreach loop to display all of these data. 我正在运行php foreach循环以显示所有这些数据。 However on each date change, I want to display the date (like groupping them design-wise).
但是,在每次更改日期时,我都想显示日期(例如按设计分组)。
So the output (on display) 所以输出(显示)
2017-08-17
1 ---- abc ---- hi ---- 2017-08-17 22:26:18
2017-08-08
1 ---- def ---- hey ---- 2017-08-08 11:57:26
1 ---- abc ---- hi ---- 2017-08-08 11:55:40
2017-07-25
1 ---- ghz ---- sup ---- 2017-07-25 16:01:34
How can I achieve this either with mySQL or PHP? 如何使用mySQL或PHP实现此目的?
Store the last date in a variable, check in every iteration: 将最后一个日期存储在变量中,检查每次迭代:
$q = "SELECT company_id, user_id, text, dateAndTime, DATE(dateAndTime) as date FROM table1 l inner join table2 d ON d.id = l.id WHERE l.company_id = 1 UNION ALL SELECT company_id, user_id, text, dateAndTime, DATE(dateAndTime) as date FROM table1 l inner join table3 p ON p.id = l.id WHERE p.company_id = 1";
// ...
$lastGroupDate = null;
foreach ($row as $company) {
if ($lastGroupDate !== $company["date"]) {
echo $company["date"]."<br>";
}
echo $company["user_id"]."<br>";
// rest of fields
$lastGroupDate = $company["date"];
}
Remember to sort the results by dateAndTime in the query. 记住要在查询中按dateAndTime对结果进行排序。
Important: you need to get DATE(dateAndTime) as date
in the query too, since you need to group them by only date (not time). 重要提示:您还需要在查询
DATE(dateAndTime) as date
,因为您只需DATE(dateAndTime) as date
日期(而不是时间)对它们进行分组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.