我搜索了这个网站和其他人,但找不到任何帮助这个问题。也许我比这更困难。
我有两张表如下。我想返回每个项目的所有信息,但只返回最新数据,并包括来自两个表格的数据
表1:serviceRequestSubmission
sid customerID
1001 11111
1002 22222
1003 33333
1004 44444
1005 55555
表2:serviceRequestHistory
historyID requestID statusUpdate
1 1001已指定
2 1002已分配
3 1003待定中
4 1004延迟
5 1002待定
6 1002已结束
我想回来:
sidID historyID statusUpdate
1001 1已分配
1002 6已结束
1003 3待定中
1004 4延迟
1005 - 已提交
我尝试了以下代码,但它返回了所有数据行,但我只想要最新/最高的历史ID。
SELECT serviceRequestSubmissions.*, serviceRequestHistory.*
FROM serviceRequestSubmissions
LEFT JOIN serviceRequestHistory ON serviceRequestSubmissions.sid = serviceRequestHistory.requestID
ORDER BY serviceRequestSubmissions.sid DESC
任何帮助将不胜感激。 谢谢!
答案 0 :(得分:0)
在查询末尾添加LIMIT子句:
LIMIT 2
答案 1 :(得分:0)
您可以在数据库中使用TIMESTAMP
或id
并获取最大TIMESTAMP
或id
值或降序TIMESTAMP
或{{1}的记录按id
子句
答案 2 :(得分:0)
SELECT serviceRequestSubmissions.*, serviceRequestHistory.*
FROM serviceRequestSubmissions
LEFT JOIN serviceRequestHistory
ON serviceRequestSubmissions.sid = serviceRequestHistory.requestID
AND historyID IN (
SELECT max(historyID)
FROM serviceRequestHistory
GROUP BY requestID
)
ORDER BY serviceRequestSubmissions.sid DESC
修改强>
仅关闭:
SELECT serviceRequestSubmissions.*, serviceRequestHistory.*
FROM serviceRequestSubmissions
JOIN serviceRequestHistory
ON serviceRequestSubmissions.sid = serviceRequestHistory.requestID
AND historyID IN (
SELECT max(historyID)
FROM serviceRequestHistory
WHERE statusUpdate = 'Closed'
GROUP BY requestID
)
ORDER BY serviceRequestSubmissions.sid DESC
答案 3 :(得分:0)
这是类型getPreferredSize()
的常见问题。我认为这是解决问题的最佳方法:
FlowLayout
这是它的工作原理:给定表greatest-n-per-group
的一行,不应该有任何其他行具有相同的SELECT
s.sid sidID,
IFNULL(h1.historyID,'-') historyID,
IFNULL(h1.statusUpdate,'Submitted') statusUpdate
FROM
serviceRequestSubmissions s
LEFT JOIN serviceRequestHistory h1 ON ( s.sid = h1.requestID )
LEFT JOIN serviceRequestHistory h2 ON ( s.sid = h2.requestID AND ( h1.historyID < h2.historyID OR h1.historyID = h2.historyID AND h1.requestID < h2.requestID ) )
WHERE
h2.requestID IS NULL
ORDER BY
s.sid
和更大的serviceRequestHistory
(后面的条件requestID
是解决关系的问题。这种解决方案通常比使用子选择更好。