我需要提取users latest 5 remarks
数据,包括他的User ID
。
所以,我使用了cross apply
并使用了RemarksData as alias
名称。
SQL查询:
select DD.DEBTOR_ID,RemarksData.*
from DMS_DEBTOR DD
cross APPLY
(
SELECT TOP 5 DF.REMARK as [Remarks]
FROM DMS_FOLLOWUP DF
WHERE DF.DEBTOR_ID = DD.DEBTOR_ID
ORDER BY DF.FOLLOWUP_TIME desc
) RemarksData where DD.BATCHNO in ('MBB EX-24') and DD.flagabort='0' order by DD.NAME
我的查询示例数据:
ID NAME Remarks
-----------------------------------------
2881173 ARIFFIN Sent To FV
2881173 ARIFFIN CHECKING PAYMENT
2881173 ARIFFIN FULLSETTLEMENT
2881173 ARIFFIN CALLED BV
2881173 ARIFFIN BROKEN PROMISE
-----------------------------------------
1682126 ASRI Waiting For Results
1682126 ASRI CHECKING PAYMENT
1682126 ASRI PROPOSAL
1682126 ASRI CALLED
1682126 ASRI BROKEN PROMISE
-------------------------------------------
1703446 ASRUL Sent To FV
1703446 ASRUL CHECKING PAYMENT
1703446 ASRUL PROPOSAL
1703446 ASRUL RNR
1703446 ASRUL BROKEN PROMISE
为了清楚了解,我已将每个用户记录分开。
在这里,您可以看到,该查询为每个用户提供了他最后5条评论。
现在,我计划将相同的查询转换为MySQL但无法找到交叉应用的替代方案。
任何人都可以建议我,如果这个SQL查询可以以任何其他方式完成或至少将其转换为MySQL。
我也试过了一些在线转换器,但没有任何对我有用。
如果需要,我可以提供其他信息。
我尝试过的MySQL查询是:
SELECT
DD.DEBTOR_ID,DD.CARDNO,DD.ACCOUNTNO,DD.NAME,
,(SELECT DF.REMARK as Remarks
FROM DMS_FOLLOWUP DF
WHERE DF.DEBTOR_ID = DD.DEBTOR_ID
ORDER BY DF.FOLLOWUP_TIME DESC
LIMIT 1
) AS VALUE
FROM
DMS_DEBTOR DD limit 10;
但是这里每个债务人(用户)只返回1条记录。但我需要最新的5条记录。如果我放LIMIT 5
,那么我就会遇到问题。
答案 0 :(得分:3)
MySQL中没有cross apply
。你也没有row_number()
(这也是表达这一点的自然方式。相反,你可以使用变量:
select DD.DEBTOR_ID,RemarksData.*
from DMS_DEBTOR DD join
(select df.debtor_id, df.remark as Remarks,
(@rn := if(@d = df.debtor_id, @rn + 1,
if(@d := df.debtor_id, 1, 1)
)
) as rn
from DMS_FOLLOWUP DF cross join
(select @rn := 0, @d := -1) params
order by df.debtor_id, df.followup_time desc
) df
on DF.DEBTOR_ID = DD.DEBTOR_ID
where DD.BATCHNO in ('MBB EX-24') and DD.flagabort = '0' and
rn <= 5
order by DD.NAME, rn;