简体   繁体   English

MYSQL查询最近的条目

[英]MYSQL Query most recent entry

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 这是我用这个查询和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. 由于某种原因,它给了我正确的16:00:00时间,但它没有给我正确的员工姓名。 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. 它与我认为的分组有关,但该组必须首先通过client_code,因为我想要每个Client_Code的最新条目。 Also I can not use ID for grouping because inputs are not always in order. 此外,我不能使用ID进行分组,因为输入并不总是有序。 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. 一旦mysql查询被纠正,我需要它计算每个员工并显示结果,如此。

Bill, 2

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 != ''

您必须在查询中添加“按id desc limit 0,1排序”,或者您可以尝试mysql_last_insert_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM