MySQL - 从表中获取三个最新日期

MySQL - Get three latest dates from tables

我有两个表:

create table product (
productid int,
productname varchar(100),
primary key(productid)
)engine=innodb;

create table purchase (
purchaseid int,
fproductid int,
customerage int,
purchasedate date,
purchasetime time,
primary key(purchaseid, fproductid),
foreign key(fproductid) references product(productid)
)engine=innodb;

现在我想获取最近的三笔购买以及购买它们的客户的年龄。我试过这个:

select * 
from product, purchase
where productid = fproductid
and purchasetime in 
 (select max(purchasetime)
 from purchase
 where year(purchasedate) = year(now())
 group by purchaseid
 order by purchasetime)
order by purchasetime limit 3;

我没有得到正确的结果。

我做错了什么?还有有没有办法让它们按时间顺序从三个中的最新到最早的顺序排列?

order by purchasetime desc limit 3;

不适合我。

谢谢!

你需要了解关系。 查询可以更简单:

SELECT * FROM purchase JOIN product ON productid = fproductid
ORDER BY purchasedate DESC, purchasetime DESC LIMIT 3;

注意:如果purchaseid是一个auto_increment PK,ORDER BY purchaseid比time

更有效率

您当前查询未返回预期结果的原因之一是 and purchasetime in (select max(purchasetime)...

MAX() 仅返回一个值,因此您最多只能得到一个结果(除非同一秒内有更多订单)