我有三个表,图书馆资料,副本和贷款。

一个图书馆项目有很多副本,而一个副本有很多借贷。

我正在尝试获取最新的贷款条目,仅用于副本;下面的查询返回给定副本的所有贷款。

SELECT
libraryitems.title,
copies.id,
copies.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM copies
INNER JOIN libraryitems ON copies.libraryitemid = libraryitems.id AND libraryitems.deletedAt IS NULL
LEFT OUTER JOIN loans ON copies.id = loans.copyid
WHERE copies.libraryitemid = 1
ORDER BY copies.id ASC, loans.createdAt DESC


我知道这里需要对某些描述进行子选择,但是努力获取正确的语法。如何只为每个不同的副本返回最新的行,即MAX(loans.createdAt)行?仅使用group by copys.id会返回最早的条目,而不是最新的条目。

下图示例:

最佳答案

在子查询中,获取贷款的最大创建时间(即最新条目),然后与贷款一起加入以获取其他详细信息。

SELECT
T.title,
T.id,
T.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM
(
   SELECT C.id, C.qruuid, L.title, MAX(LN.createdAt) as maxCreatedTime
   FROM Copies C
   INNER JOIN libraryitems L ON C.libraryitemid = L.id
   AND L.deletedAt IS NULL
   LEFT OUTER JOIN loans LN ON C.id = LN.copyid
   GROUP BY C.id, C.qruuid, L.title) T
 JOIN loans ON T.id = loans.copyid
AND T.maxCreatedTime = loans.createdAt

关于mysql - 需要使用mySQL Sub Select,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26699209/

10-17 03:06