获取插入sql的最新行以获取特定ID

时间:2015-10-20 06:22:22

标签: php mysql sql

我正在创建当前薪资报告

这是我的疑问:

$sql = "SELECT *
FROM payroll, employees
WHERE employees.username='$username'
AND payroll.id=employees.id";

输出是: output并向下滚动this is the continuation of the output

总结一下,查询显示某个ID的所有记录,但我希望它在数据库中显示该特定ID的最后插入数据。怎么会发生这种情况?

4 个答案:

答案 0 :(得分:1)

要获取最新的行,您必须按id desc订购,并且只能获得一个记录集limit 1

所以代码将是

$sql = "SELECT *
FROM payroll, employees
WHERE employees.username='$username'
AND payroll.id=employees.id ORDER BY employees.id DESC LIMIT 1 ";

答案 1 :(得分:0)

试试这个

$sql = "SELECT *
FROM payroll, employees
WHERE employees.username='$username'
AND payroll.id=employees.id ORDER BY employees.id DESC  LIMIT 1 " 

如果最新的ID是最大值。

答案 2 :(得分:0)

使用此MySQL ORDER BY LIMIT

$sql = "SELECT *
FROM payroll, employees
WHERE employees.username='$username'
AND payroll.id=employees.id ORDER BY employees.id DESC LIMIT 1";

答案 3 :(得分:0)

$sql = "SELECT t1.*,t1.*
FROM payroll t1 join employees t2 on t1.id = t2.id
WHERE t1.username='$username' order by t2.id desc limit 1";