我有一个非常复杂的查询,让我的大脑融化。
SELECT abunchOfStuff, r.xyz as netsell
FROM normalmtm n
JOIN mtmprogram m ON (
m.mtmprogram = n.loanprogram
AND m.investor = 'Xyzzy'
)
JOIN rates as r on (
r.term >= '2012-01-01'
AND r.investor = m.investor
AND r.rate = n.rate
AND r.program = m.basenormal
AND r.clientcode = n.clientcode
)
LEFT OUTER JOIN mtmadjustments as ad ON (
ad.loannumber = n.loannumber
AND ad.investor = m.investor
)
WHERE n.loannumber = '12345678'
AND n.clientcode = 10
ORDER BY netsell DESC LIMIT 1
这是从一堆中选择最大的netsell。现在,我无法解决的棘手问题是费率表在n.clientcode上可能匹配也可能不匹配。如果它不匹配,我想使用0的客户端代码,它本质上是一个通配符。
现在我正在进行特定于客户端代码的查询,如果它没有返回任何内容,我再次使用clientcode = 0进行此查询......似乎我可以将这两个东西以某种方式包装在一起。
我查看了EXISTS或NOT EXISTS子查询,但我在这个例子中无法弄清楚如何使用它,我甚至不确定它是否合适。
感谢任何帮助!
答案 0 :(得分:0)
在连接中的客户端代码上应用的IFNULL()应该做的伎俩
AND r.clientcode = IFNULL(0, n.clientcode)
编辑:也许我完全不理解你的问题...你说你不匹配时你想要零,所以最初我建议一个选项,当该字段为空时,所以你得到零以匹配r.clientcode。当第二个为空时,IFNULL输出第一个值,而当它不为空时,输出第二个值,就是那个。
但是,如果你需要做1.)检查它们是否匹配,2。)如果它们匹配,则加入,3。)如果它们不匹配,则加入零值......你可能需要一个子查询< / p>
AND r.clientcode = ( IFNULL(0, select nn.clientcode FROM normalmtm nn where r.clientcode = nn.clientcode and nn.clientcode=n.clientcode) )
类似的东西,也许......
答案 1 :(得分:0)
SELECT abunchOfStuff, ISNULL(r.xyz, r2.xyz) as netsell
FROM normalmtm n
JOIN mtmprogram m ON (
m.mtmprogram = n.loanprogram
AND m.investor = 'Xyzzy'
)
LEFT OUTER JOIN rates as r on (
r.term >= '2012-01-01'
AND r.investor = m.investor
AND r.rate = n.rate
AND r.program = m.basenormal
AND r.clientcode = n.clientcode
)
LEFT OUTER JOIN rates as r2 on (
r2.term >= '2012-01-01'
AND r2.investor = m.investor
AND r2.rate = n.rate
AND r2.program = m.basenormal
AND r2.clientcode = 0
)
LEFT OUTER JOIN mtmadjustments as ad ON (
ad.loannumber = n.loannumber
AND ad.investor = m.investor
)
WHERE n.loannumber = '12345678'
AND n.clientcode = 10
ORDER BY netsell DESC LIMIT 1