获取MySQL数据库中每个ID的最新(日期)记录

时间:2015-08-14 10:33:42

标签: php mysql date select max

我正在将住在一所房子里的人添加到数据库中。 8月1日有人搬进1号房子,8月5日有人搬进4号房子,8月10日有人再搬进1号房子。我想在页面上显示的是居住在房子里的人,例如8月9日和8月11日。

数据库示例:

employee----house-date
1-----------2-----01-01-2012
5-----------7-----01-01-2012
1-----------1-----01-08-2012
3-----------4-----01-01-2012
1-----------8-----01-09-2012

首先我试过

SELECT employee FROM habitants WHERE house='$house' AND date <= '$today' ORDER BY date DESC, employee ASC

但是这显示了一个人在多个房子里(例如,当雇员1有时改变房屋时)

然后我试了

SELECT employee FROM habitants WHERE house='$house' AND date <= '$today' ORDER BY date DESC, employee ASC LIMIT 1

但是我每个家只有一个人

然后我在MAX上发现了一些东西,所以我尝试了

SELECT employee, MAX(date), house FROM habitants WHERE house='$house' AND date <= '$today' ORDER BY date DESC, employee ASC GROUP BY house

这导致以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY huis' at line 1

有人能告诉我如何以正确的方式做到这一点吗?谢谢!

1 个答案:

答案 0 :(得分:3)

一种方法是使用子查询和join

SELECT h.*
FROM habitants h JOIN
     (SELECT house, MAX(date) as maxd
      FROM habitants
      WHERE date <= '$today'
      GROUP BY house
     ) hh
     ON hh.house = h.house and hh.maxd = h.date
WHERE house = '$house'; 

您也可以将其写为相关子查询:

SELECT h.*
FROM habitants h
WHERE h.house = $house AND
      h.date = (SELECT MAX(date)
                FROM habitants h2
                WHERE h2.house = h.house and h2.date <= CURDATE()
               );

请注意,在大多数情况下,您无需传入当前日期。 CURDATE()提供当前日期(NOW()是当前时间。)

编辑:

如果您正在查看员工的位置,那么您需要找到每位员工的最长日期,而不是房子:

SELECT h.*
FROM habitants h
WHERE h.house = $house AND
      h.date = (SELECT MAX(date)
                FROM habitants h2
                WHERE h2.employee = h.employee and h2.date <= CURDATE()
               );

或者,或者:

SELECT h.*
FROM habitants h JOIN
     (SELECT employee, MAX(date) as maxd
      FROM habitants
      WHERE date <= '$today'
      GROUP BY employee
     ) hh
     ON hh.employee = h.employee and hh.maxd = h.date
WHERE h.house = '$house';