我想从表tblquoteproposal`中检索最近的requestid
以获取特定的customerId这里3,在这个例子中ID 2& ID 4。
表tblrequest requestid Customerid 6 2 7 4 8 3 9 3
表tblquoteproposal
id requestid QuotePraposalLink comment
1 6 jgj mghm
2 7 jhgj hjgj
3 8 xyz1 rifsf
*4 8 xyz2 ri2sf*
5 9 xyz3 ri3sf
*6 9 xyz4 ri4sf*
在此表中requestid
是外键。
还有另一个表tblrequest
,其中requestid
为主键。
我写了以下查询,但它没有给我正确的结果:
SELECT r.RequestId,r.ConsultantId,(SELECT concat(FirstName,' ',LastName)
FROM tbluser
WHERE UserId = v_userId) as "Customer",
r.RequestDate,r.QuoteDetailsFileLink,r.Requestcomment,r.CustomerId,
qp.QuotePraposalLink,qp.Comment
FROM tblrequest r
LEFT OUTER JOIN tblquoteproposal qp ON r.RequestId=qp.RequestId
WHERE r.customerid=v_userId
GROUP BY r.RequestId
ORDER BY qp.id ;
答案 0 :(得分:2)
为什么不尝试:
SELECT MAX(id)
FROM tblquoteproposal
GROUP BY requestid
并将此查询的结果提供给您需要的任何内容? (这可以是子查询)。
例如,您的完整解决方案可能如下(我使用LEFT OUTER JOIN,因为您这样做,我不确定它是正确的方式,也许INNER JOIN更合适):</ p>
SELECT ... your fields ...
FROM
tblquoteproposal p LEFT OUTER JOIN tblrequest r
on p.requestid = r.requestid
WHERE p.id IN (
SELECT MAX(id)
FROM tblquoteproposal
GROUP BY requestid )
答案 1 :(得分:0)
SELECT *
FROM (
SELECT requestid, MAX(id) AS mid
FROM tblquoteproposal
GROUP BY
requestid
) m
JOIN tblrequest tr
ON tr.id = tm.requestid
JOIN tblquoteproposal tqp
ON tqp.id = m.mid
答案 2 :(得分:0)
Rax Olgud的优化版本答案可能是:
SELECT ... your fields ...
FROM
tblquoteproposal p LEFT OUTER JOIN tblrequest r
ON p.requestid = r.requestid
WHERE p.id = ifnull( (
SELECT MAX(id)
FROM tblquoteproposal
where requestid = r.requestid ), p.id )
编辑使其成为外部联接。