用加入替换mysql变量
我正在使用MySQL 5-Enterprise-Commercial
版本。 我写了以下2个查询,我想使用JOIN转换为单个查询。
SET @row_number :=0;
SELECT
@row_number:= case
when @RId = r_id then @row_number + 1
else 1
end as rnum,
@RId:=r_id as r_id,
msg,
supplier,
rrtry from (
SELECT
a.r_id as r_id,
mta.message as msg,
tpr.supplier as supplier,
trw.retry as rrtry,
a.createdAt as createdAt,
FROM sa.nra a,
sa.nmta mta,
sa.treq tpr,
sa.twflw trw
WHERE tpr.n_r_id = a.r_id
AND trw.astp = mta.stp
AND mta.rstatus in ('FAIL')
AND tpr.p_w_id = trw.id
AND a.a_mid = mta.id
AND a.createdAt BETWEEN now() - interval 30 DAY AND now()
ORDER BY a.r_id
) as sa
HAVING rnum = 1
ORDER BY createdAt DESC;
基本上,r_id
有多个条目,我想获得特定r_id
的最新条目,这就是为什么我通过a_createDeDat desc <使用订单/代码>
I am using MySQL 5-enterprise-commercial
version.
I have written the below 2 queries which I want to convert into a single query using join.
SET @row_number :=0;
SELECT
@row_number:= case
when @RId = r_id then @row_number + 1
else 1
end as rnum,
@RId:=r_id as r_id,
msg,
supplier,
rrtry from (
SELECT
a.r_id as r_id,
mta.message as msg,
tpr.supplier as supplier,
trw.retry as rrtry,
a.createdAt as createdAt,
FROM sa.nra a,
sa.nmta mta,
sa.treq tpr,
sa.twflw trw
WHERE tpr.n_r_id = a.r_id
AND trw.astp = mta.stp
AND mta.rstatus in ('FAIL')
AND tpr.p_w_id = trw.id
AND a.a_mid = mta.id
AND a.createdAt BETWEEN now() - interval 30 DAY AND now()
ORDER BY a.r_id
) as sa
HAVING rnum = 1
ORDER BY createdAt DESC;
Basically, there are multiple entries for r_id
, and I want to get the latest entry for a particular r_id
and that is why I am using ORDER BY a_createdAt DESC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用使用
:=
运算符设置变量的子查询加入查询。我已经用ANSI Join代替了子查询中的交叉产品。
如果您使用的是MySQL 8.0,则可以使用
rank()
或row_number()
窗口函数而不是用户变量。Join the query with a subquery that uses the
:=
operator to set the variable.I've replaced the cross-product in the subquery with ANSI JOIN.
If you're using MySQL 8.0, you can use the
RANK()
orROW_NUMBER()
window functions instead of a user variable.