我有一些业务规则,我需要查询数据库。现在,下面的sql正在使用子查询,但我想将每个查询更改为连接语句。
我的数据库是DB2,但我使用mysql创建了一个sql小提琴 http://www.sqlfiddle.com/#!9/3d10ae/3
我需要检查客户是否在过去60天内购买了商品编号1025926 如果查询返回结果,则客户购买该项目。
SELECT ord1.oditnr, ord1.odredt, itm.imdesc
FROM orderdetails ord1
LEFT JOIN items itm ON ord1.oditnr = itm.imitnr
WHERE EXISTS (SELECT *
FROM orderdetails ord2
WHERE ord1.odbcsn = ord2.odbcsn
AND ord2.oditnr = '1022925'
AND odredt >= VARCHAR_FORMAT(CURRENT TIMESTAMP - 60 DAYS, 'YYYYMMDD') )
AND ord1.odbcsn = '11677'
ORDER BY odredt desc ;
我需要检查客户是否在过去60天内没有购买商品编号2521809 如果查询返回结果,则客户尚未购买该项目。
SELECT ord1.oditnr, ord1.odredt, itm.imdesc
FROM orderdetails ord1
LEFT JOIN items itm ON ord1.oditnr = itm.imitnr
WHERE NOT EXISTS (SELECT *
FROM orderdetails ord2
WHERE ord1.odbcsn = ord2.odbcsn
AND ord2.oditnr = '2521809'
AND odredt >= VARCHAR_FORMAT(CURRENT TIMESTAMP - 60 DAYS, 'YYYYMMDD') )
AND ord1.odbcsn = '11677'
ORDER BY odredt desc ;
答案 0 :(得分:-1)
如果找不到支持子查询的其他工具,可以尝试以下操作:
SELECT ord1.oditnr, ord1.odredt, itm.imdesc
FROM orderdetails ord1
INNER JOIN orderdetails ord2
ON ord1.odbcsn = ord2.odbcsn
LEFT JOIN items itm ON ord1.oditnr = itm.imitnr
WHERE ord2.oditnr = '1022925'
AND ord2.odredt >= (CURDATE() - interval 60 day + 0)
AND ord1.odbcsn = '11677'
ORDER BY odredt desc ;
-- Updated this query
SELECT ord1.oditnr, ord1.odredt, itm.imdesc
FROM orderdetails ord1
LEFT JOIN orderdetails ord2
ON ord1.odbcsn = ord2.odbcsn
LEFT JOIN items itm ON ord1.oditnr = itm.imitnr
WHERE ord2.oditnr = '2521809'
AND ord2.odredt >= (CURDATE() - interval 60 day + 0)
AND ord1.odbcsn = '11677'
ORDER BY odredt desc ;
更新:我调整了底部查询,将INNER JOIN更改为LEFT JOIN。但是,与OP发布的查询不同,如果找不到ord2.oditnr,则此版本返回空集 - 这在直觉上是有意义的 - 如果未找到订单号,则不返回任何行。如果没有某种子查询,确实没有办法根据非
返回集合至少,顶部查询与OPs输出匹配。