douchensou6969 2010-11-17 16:00
浏览 65
已采纳

MYSQL查询最近的条目

Here is the problem. I need to transform this query to get the right information and Im not sure how.

Database info

   Id    |   Client_Code   |  Time_Date          | Employee_Name | Date_Time | Time_Stamp  
    1    |    000010       |  2010-11-17 07:45:00| Jerry         | 2010-11-17| 07:45 AM
    2    |    000022       |  2010-11-17 07:30:00| Jerry         | 2010-11-17| 07:30 AM
    3    |    000010       |  2010-11-17 16:00:00| Bill          | 2010-11-17| 04:00 PM
    4    |    000022       |  2010-11-17 16:00:00| Bill          | 2010-11-17| 04:00 PM

Here is the query

$sql = "SELECT Client_Code, MAX(TIME(Time_Date)), Employee_Name, Date_Time, Time_Stamp FROM Transaction WHERE Date_Time = CURdate()
                    AND Time_Stamp != '' GROUP BY Client_Code"; 

Here is what i get with this query and phpcode

echo " $row[Employee_Name], $row[Client_Code], ".$row['MAX(TIME(Time_Date))']."<br>";
Jerry, 000010, 16:00:00
Bill, 000022, 16:00:00

For some reason yes its giving me the right 16:00:00 Time but it is not giving me the right employee name with that time. It has something to do with the grouping I think but the group has to be by client_code first because I want the most recent entry for each Client_Code. Also I can not use ID for grouping because inputs are not always in order. Here is what is should look like.

Bill, 000010, 16:00:00
Bill, 000022, 16:00:00

Can anyone tell me how to fix this query to get the correct information please. Also once the mysql query is corrected Ill need it to count each employee up and display the results like so.

Bill, 2
  • 写回答

2条回答 默认 最新

  • dsykx64220 2010-11-17 16:48
    关注

    Use a self join:

    SELECT x.client_code,
           TIME(x.time_date)
           x.employee_name,
           x.date_time,
           x.time_stamp
      FROM TRANSACTION x
      JOIN (SELECT t.client_code,
                   MAX(t.time_date) AS max_time_date
              FROM TRANSACTION t
             WHERE t.date_time = CURRENT_DATE
               AND t.time_stamp != ''
          GROUP BY t.client_code) y ON y.client_code = x.client_code
                                   AND y.max_time_date = x.time_date
     WHERE x.date_time = CURRENT_DATE
       AND x.time_stamp != ''
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算