根据列值的变化向MySQL查询结果添加空行

根据列值的变化向MySQL查询结果添加空行,mysql,sql,formatting,Mysql,Sql,Formatting,如果我有一个典型的MySQL查询,例如: SELECT CommentNo, CreatedDate, CreatedTime, Text FROM Comment 结果将显示在一个简单的表格中。但是有没有可能让MySQL格式化输出,以便根据列中的更改在结果中插入一个空行 因此,如果上面的查询默认返回以下内容: CommentNo CreatedDate CreatedTime Text 1 2012-08-02 15:33:27 This. 2

如果我有一个典型的MySQL查询,例如:

SELECT CommentNo, CreatedDate, CreatedTime, Text FROM Comment
结果将显示在一个简单的表格中。但是有没有可能让MySQL格式化输出,以便根据列中的更改在结果中插入一个空行

因此,如果上面的查询默认返回以下内容:

 CommentNo CreatedDate CreatedTime Text
 1         2012-08-02  15:33:27    This.
 2         2012-08-02  15:34:40    That.
 3         2013-06-30  19:45:48    Something else.
 4         2013-06-30  21:26:01    Nothing.
 5         2013-06-30  21:26:43    Was.
 6         2013-07-01  13:40:32    Hello.
 7         2013-07-01  14:08:25    Goodbye.
是否可以在更改
CreatedDate
的列值时插入一个空行,因此我得到:

 CommentNo CreatedDate CreatedTime Text
 1         2012-08-02  15:33:27    This.
 2         2012-08-02  15:34:40    That.

 3         2013-06-30  19:45:48    Something else.
 4         2013-06-30  21:26:01    Nothing.
 5         2013-06-30  21:26:43    Was.

 6         2013-07-01  13:40:32    Hello.
 7         2013-07-01  14:08:25    Goodbye.  
以上不是数据在注释表中的存储方式,而是格式化查询输出的问题


或者在Java中使用
BufferedWriter
更好吗?

首先,我要说的是,这种格式肯定应该在应用程序层完成,而不是作为查询

也就是说,这似乎是一个有趣的练习,而且并不难:

select CommentNo, CreatedDate, CreatedTime, Text
from (select c.*, CreatedDate as key1, 0 as ordering
      from comment c
      union all
      select c2.*, c.CreatedDate, 1
      from (select distinct CreatedDate from comment c) c left join
           comment c2
           on 1 = 0
     ) c
order by key1, ordering, id;

请注意,在第二个子查询中使用了
left join
来引入所有列,因此它与第一个子查询中的
select*
匹配。但是,要去掉最后两列,仍然需要列出所有列。

我修改了:中的代码,在解析数据以写入.csv文件时,该代码可以轻松扩展为包含一行

// Iinitialise FileWriter object.
        fileWriter = new FileWriter(fileName);

        // Iinitialise CSVPrinter object/ t.
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        // Create .csv file header.
        csvFilePrinter.printRecord(FILE_HEADER);

        // Write a new student object list to the .csv file.
        for (Student student : students) {
            ArrayList studentDataRecord = new ArrayList();
            studentDataRecord.add(String.valueOf(student.getId()));
            studentDataRecord.add(student.getFirstName());
            studentDataRecord.add(student.getLastName());
            studentDataRecord.add(student.getGender());
            studentDataRecord.add(String.valueOf(student.getAge()));
            csvFilePrinter.printRecord(studentDataRecord);
            csvFilePrinter.println();
        }

虽然我还没有添加代码来确定所需列值的更改,但这很简单。

这是可能的,但在数据库级别这样做是一个非常糟糕的主意。这应该是表示代码的一部分。这将在MySQL查询输出的格式中。理想情况下,我希望在将数据写入CSV文件时包含空白行。空格不会存储在数据库表中。您可以使用偏移量值在数据库中插入空格。但这不是一种理想的数据存储方式。同样,数据不会以空行存储。我的问题只涉及查询输出。同样,这是可能的,但不要让数据库进行这种格式化,即使是查询输出。无论程序向MySQL发送查询,都应该在写入CSV数据时获取结果并插入空行。我喜欢这一点,但我同意它不包括在数据库级别。但我选择了另一种方法,并将其作为我的解决方案发布。答案与问题不同,问题只涉及SQL语句。