mysql - 对此可以优化的查询是什么?

标签 mysql

我陷入了小查询。有一个名为 Table_Activities 的表。

Table_Activities(Act_idDate、Activity_name说明)。

我们需要据此生成一份报告。用户将从下拉列表中选择他想要生成报告的

我们需要按事件名称显示该月和该年组的所有事件。

示例 - 用户选择六月2012

报告将是-

园艺

01/06/2012 - They have planted 100 trees.
14/06/2012 - something
27/06/2012 - something

培训

02/06/2012 - Detail description
15/06/2012 - something
28/06/2012 - something

我的问题是用什么mysql查询来获取这种格式的数据?

最佳答案

select `Date`,description from tm_activities 
where month(`Date`)='6' and year(`Date`)='2012' 
order by Activity_name,`date` 

要返回问题中所示的确切格式,请尝试以下操作:

select concat(if(actdate='',activity_name,date_format(actdate,'%d/%m/%y')),if(description<>'',concat(' - ',description),'')) as labelm from
(
(select ActDate,description,activity_name from tm_activities where month(ActDate)='6' and year(ActDate)='2012' 
) 
union all
(Select distinct '','',activity_name from tm_activities where month(ActDate)='6' and year(ActDate)='2012')
)m order by activity_name,actdate
;

SQL FIDDLE HERE.

输出如下:

Gardening
01/06/12 - They have planted 100 trees.
27/06/12 - Gar 2
Training
12/06/12 - Training 1
28/06/12 - Traning 2
30/06/12 - Traning 3

关于mysql - 对此可以优化的查询是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11929131/

相关文章:

java - 如何使用 Struts 2 <s :file> tag 在数据库中插入图像

php - 在 MySQL 中连接 3 个表会产生带有值的重复行

c++ - 为什么 std::bad_alloc 会被 get_driver_instance() 抛出?

mysql - 如何查找一个表中确实存在于另一个表中但基于日期的记录?

MySQL 在 where 子句中使用内部查询

mysql - Flask SQL-Alchemy 查询为我的数据库中存在的数据返回空值。可能是什么原因

php - fetch_array() 不保留查询中的 ORDER BY

mysql - UPDATE table1 SET column1 = (SUM(table2{& table3} WHERE table2_id1 = id1) WHERE id1 = table2_id1

mysql - 关于数据库更新/插入速率限制的一些查询(基于 SQL 或基于 NoSQL)

python - 为什么我会收到此错误 : _mysql_exceptions. OperationalError : (1241, 'Operand should contain 1 column(s)' )