问题
I have 2 columns in a table in mysql which looks sometime like below,
title timestamp
--------------------
test1 1/7/2012
test2 1/7/2012
test3 1/7/2012
test4 2/7/2012
test5 3/7/2012.
The result I am looking for is something like,
**1/7/2012**
test1
test3
**2/7/2012**
test4
**3/7/2012**
test5
Can someone help him here.can this be done just with MySQL query or I need to iterate the resultset in server side and then format the resultset for displaying.
回答1:
You can use a query like this one:
select title,timestamp,str_to_date(timestamp, '%d/%m/%Y') as date from table_name order by date,title;
iterating over the result set and printing the timestamp only when it changes.
str_to_date is a MySQL function which converts a string to a date, useful for sorting. If you are not using MySQL, you should check for an analogous function.
回答2:
If I understood correctly what you want, the code should look like this:
int itemsInPage = 100; //Number of item to display in page
int currentPage = 1; //Index of current page, starting from 1
PreparedStatement ps = con.prepareStatement("select title,timestamp,str_to_date(timestamp,'%d/%m/%Y') as date from table_name order by date,title limit " + ((currentPage - 1) * itemsInPage) + ", " + itemsInPage);
ResultSet rs = ps.executeQuery();
String prevTimestamp = null;
while(rs.next()) {
if (prevTimestamp == null || !prevTimestamp.equals(rs.getString(2))) {
System.out.println("*** "+rs.getString(1)+" ***");
}
System.out.println(rs.getString(1));
prevTimestamp = rs.getString(2);
}
If you are coding in a jsp, you should use
out.print(...);
instead of
System.out.println
来源:https://stackoverflow.com/questions/11484680/display-data-based-on-date