我有一个包含 3 列的表:
id (int)name (String)date_created (Date)
如何根据date_created列选择添加到数据库的姓氏?
SQL 服务器:
SELECT TOP 1 name
FROM dbo.TableName
ORDER BY date_created DESC
MySQL:
SELECT name
FROM dbo.TableName
ORDER BY date_created DESC
Limit 1
TOP 1 WITH TIES如果要在多行具有相同的date_created最大值时包含所有数据,则可以在 T-SQL 中使用。在 MySQL 上,您需要使用子查询。这是一个例子。
试试这个:
SELECT name FROM table
WHERE date_created = (SELECT MAX(date_created) FROM table)
如果你有一个自动递增的(SQL Server 中的身份)id,那么你可以使用它来代替:
select name
form table
order by id desc
limit 1
当然,limit 1取决于数据库。它将select top 1在 SQL Server、where rownum = 1Oracle 和fetch first 1 rowdb2 中。
您还可以使用子查询:
select t1.id, t1.name, t1.date_created
from yourtable t1
inner join
(
select max(date_created) MaxDate
from yourtable
) t2
on t1.date_created = t2.maxdate
这将返回所有具有max(created_date)