这是我现在的询问:
SELECT
a.stacct, b.hacct, a.stfrqcode, b.thfrqcode
FROM st a
LEFT JOIN th b
ON b.hacct = a.stacct
问题:我有第三个表,每个stfrqcode与每个thfrqcode的关系(例如ax = d4);问题是如何撤回所有内容并告诉它们是否匹配?在参考表中有两列stfrqcode和thfrqcode - 它们在每列中都有不同的值。
stacct,
stfrqcode
hacct,
thfrqcode
thfrqcode,
stfrqcode
ns x00
ed x22
zs x33
ao x44
结果集应该是: 如果stfrqcode和thfrqcode之间存在匹配,那么stacct,hacct和基本上是yes / no。
答案 0 :(得分:3)
SELECT
a.stacct
,b.hacct
,case when c.stfrqcode is null then 'No' else 'Yes' end IsMatch
from st a
left outer join th b
on b.hacct = a.stacct
left outer join ThirdTable c
on c.stfrqcode = a.stfrqcode
and c.thfrqcode = b.thfrqcode
...可能在那里有一些拼写错误,我无法调试它。
答案 1 :(得分:1)
假设我理解你的表结构(我创建了一些虚拟值):
表格st
stacct stfrqcode
fred A
mary B
joseph C
表格
hacct thfrqcode
fred J
mary H
表关系
stfrqcode thfrqcode
A J
B Q
你想要这个解决方案(我删除了hacct,因为值只能等于stacct,如果没有匹配则为null):
stacct match
fred yes
mary no
joseph no
这是我要尝试的查询:
SELECT
a.stacct, (CASE WHEN c.strfrqcode IS NULL THEN 'no' ELSE 'yes' END) AS match
FROM st a
LEFT JOIN th b
ON b.hacct = a.stacct
LEFT JOIN relation c
ON c.strfrqcode = a.strfrqcode and c.thfrqcode = b.thrfrqcode and b.thrfrqcode IS NOT NULL
答案 2 :(得分:0)
如果你的frqcodes表在(stfrqcode,thfrqcode)上不一定是唯一的,或者只是因为你可以,你可能想在选择列表中尝试一个exists子句:
SELECT a.stacct, b.hacct, a.stfrqcode, b.thfrqcode,
CASE WHEN EXISTS (SELECT 1
FROM frqcodes AS c
WHERE c.stfrqcode = a.stfrqcode
AND c.thfrqcode = b.thfrqcode)
THEN 'Yes'
ELSE 'No'
END AS relationship_exists
FROM st a
LEFT JOIN th b
ON b.hacct = a.stacct