然后通过设置最新日期的值来设置mysql

时间:2012-06-19 14:27:27

标签: mysql perl email variables

我目前正在制作一个程序,如果最后一个人的日期结束(某个时间范围),将发送电子邮件。我的桌子布局如下:

employee   | dept. | date       | other | 
bob        | 1     | 2012-05-29 | abc   |
bob        | 1     | 2012-07-15 | xyz   |
jon        | 2     | 2012-05-29 | abc   |

(我已按员工排序,然后按日期排序) 所以例如,对于bob我想自动将变量分配给2012-07-15日期,因为那是他最后一次输入的日期。然后根据我想发送电子邮件的当前日期,如果提交之间的时间已经很长。我的问题是如何将变量分配给表中每个人的最后日期?我也对不同的更好的方法持开放态度。谢谢。

2 个答案:

答案 0 :(得分:1)

要返回每位员工的最新日期,这样的事情就可以了。

SELECT employee
     , MAX(`date`) AS latest_date
  FROM mytable
 GROUP BY employee
 ORDER BY employee

附录,

正如simbabque所指出的,这适用于获取最新日期,但不会返回other值。获得该结果集有两种方法。

如果我们保证(employee,date)是UNIQUE(例如,通过唯一约束),我们可以返回具有最新日期的行上的其他列,并使用如下查询:

SELECT t.employee, t.`date`, t.other
 FROM mytable t
 JOIN ( SELECT r.employee, MAX(r.`date`) AS latest_date
         FROM mytable r
        GROUP BY r.employee
      ) s
   ON s.employee = t.employee
  AND s.latest_date = t.`date`
ORDER BY t.employee

如果我们不能保证(员工,日期)是唯一的,那么这个查询就不够了。但是有几种方法可以解决这个问题。

答案 1 :(得分:1)

这是Perl的解决方案。 SQL查询的功劳归于@ spencer7593。

如果您不熟悉DBI,我建议您快速浏览一下。另请查看DBD::mysql以了解如何创建数据源(DSN)。

您基本上需要连接到数据库,准备查询,执行它并获取结果。然后,您可以使用它们发送电子邮件。

以下是一个不包含实际发送电子邮件的简单示例:

use strict;
use warnings;
use DBI;
require 'script_that_has_custom_email_sub.pl'; # or use a module or whatever

# create the database handle
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost", # <-- DSN
                       'username', 'password')
            or die $DBI::errstr;

# prepare the query to get a statement handle
my $sth = $dbh->prepare(<<__SQL__
SELECT employee
     , MAX(`date`) AS latest_date
  FROM mytable
 GROUP BY employee
 ORDER BY employee
__SQL__
);
$sth->execute; # send the query to the mysql server

# fetch each row of the result as a hashref
while (my $res = $sth->fetchrow_hashref) {
  # access $res with the keys employee and latest_date from the query
  # and send the mail
  &custom_send_email_sub($res->{'employee'}, $res->{'latest_date'});
}
$sth->finish;
相关问题