如何检索相同的列数据并显示为组

时间:2013-07-13 13:47:42

标签: php mysql

名为users_log的表包含用户登录和注销时间和日期,但我无法按照我的意图对数据进行排序。

  

查询

mysql_query('SELECT * FROM users_log WHERE u_id = 52 ORDER BY date_log')
  

对数据进行排序,如

Fri 12 Jul 13 - 03:41:40 PM - 03:42:31 PM

Fri 12 Jul 13 - 05:35:40 PM - 05:42:31 PM

Sat 13 Jul 13 - 02:29:09 PM - 02:34:52 PM
  

users_log表

log_id, u_id,  date_log,   logged_date,   login_time,   logout_time

2,      52,   2013-01-12, Fri 12 Jul 13,  03:41:40 PM,  03:42:31 PM
  

因为我打算显示数据

         Fri 12 Jul 13
   03:41:40 PM - 03:42:31 PM
   05:35:40 PM - 05:42:31 PM
         Sat 13 Jul 13
   02:29:09 PM - 02:34:52 PM

2 个答案:

答案 0 :(得分:3)

这样做:

$result = mysql_query('SELECT * FROM users_log WHERE u_id = 52 ORDER BY date_log');
$sorting = array();
while($row = mysql_fetch_assoc($result))
{
    $sorting[$row['logged_date']][] = $row['login_time']."-".$row['logout_time'];
}

//Now you loop over the sorted data using foreach($sorting as $key => $value) and display it any way you want.

我希望这可以提供一些帮助。

答案 1 :(得分:1)

恕我直言,你应该做一些事情(我假设你想在php中做到这一点):

SELECT date_log FROM users_log WHERE u_id = 52 GROUP BY date_log,

然后迭代结果(在php中)并获取相应的日期行:

SELECT * FROM users_log WHERE u_id = 52 AND date_log = $date_for_current_iteration ORDER BY date_log;