我如何找到最后输入的记录

时间:2015-03-13 21:02:56

标签: mysql

我有两张桌子:与会者&历史。历史记录表是我为所有与会者发布付款的地方。它还存储historyid和参与者。我用来尝试访问特定与会者的历史记录表中输入的最后一条记录的查询是:

$stmt = $db->prepare('SELECT a.fname, a.lname, h.amount, h.subsidy, h.last_payment, h.balance 
                        FROM history AS h
                        INNER JOIN  
                        attendees AS a
                        ON a.attendeeid = h.attendeeid
                        WHERE a.attendeeid = :id
                        ORDER BY historyid DESC LIMIT 1)');
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll();

但是代码根本没有返回任何内容。由于历史记录可能比我想要检索的历史记录更大,我如何将该参与者的最大历史记录关联起来,以便在历史记录表中为他们输入最后一条记录?我正在使用的显然不是答案。在此先感谢您的帮助。

对不起。架构是:

TABLE attendees ( attendeeid int(10) unsigned NOT NULL AUTO_INCREMENT, fname varchar(20) NOT NULL, lname varchar(20) NOT NULL, dojid varchar(10) NOT NULL, address1 varchar(25) NOT NULL, address2 varchar(25) NOT NULL, city varchar(20) NOT NULL, state char(2) NOT NULL, zipcode varchar(5) NOT NULL, phonenumber varchar(15) NOT NULL, memberid int(10) unsigned NOT NULL, PRIMARY KEY (attendeeid), KEY memberid (memberid), CONSTRAINT attendees_ibfk_2 FOREIGN KEY (memberid) REFERENCES members (memberid) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

attendees

attendeeid

2 个答案:

答案 0 :(得分:0)

请您提供两个表格的结构吗?我猜你的表包含日期列,或类似的东西。

无论如何,我会尝试类似的事情:

select * 
from (select a.attendeeid,max(h.id) 
      FROM history AS h INNER JOIN attendees AS a ON a.attendeeid = h.attendeeid
      group by a.attendeeid) as maxHistoryPerAttendee 

通过这种方式,您将获得每位参加者的最大历史记录ID。我猜最大ID,是最后插入的行。

答案 1 :(得分:0)

这是您添加了几个字段的查询: select * from (select a.attendeeid,max(h.historyid),fname,lname,last_payment,amount FROM history AS h INNER JOIN attendees AS a ON a.attendeeid = h.attendeeid group by a.attendeeid) as maxHistoryPerAttendee where attendeeid = 29

在这样做时,我得到了该与会者的last_payment的第一行条目,而不是与MAX(historyid)行关联的last_payment。

要添加到此并调用它,我就可以使用它了。它非常接近我的原始查询。

$stmt = $db->prepare('SELECT fname, lname, amount, subsidy, last_payment, balance, a.attendeeid, h.historyid FROM history AS h INNER JOIN attendees AS a ON a.attendeeid = h.attendeeid where h.attendeeid = :id ORDER BY h.historyid DESC LIMIT 1'); $stmt->bindValue(':id', $id, PDO::PARAM_INT); $stmt->execute();

像冠军一样工作!