如果当前不存在,则在另一个 table 中搜索值
Search a value in another table if doesnt exist in the current
我有一个 table,我想搜索列中是否有值。如果它不存在,我想在另一个 table 中搜索它。
我试过了:
SELECT *,
CASE(WHEN student = 'ted' THEN 'ted'
ELSE ( SELECT student
FROM dbo.class2
WHERE student= 'ted')) END AS ISOK
from dbo.class1
因此,如果 dbo.class1.student
不是 'ted',则 ISOK
列将从 dbo.class2.student
中获取值。
尽管上面的查询是错误的,因为它 returns 更多值。
我很确定我尝试做的方法是错误的。
你能试试这个吗?
SELECT
NVL(a.student, b.student) ISOK
FROM dbo.class1 a
FULL OUTER JOIN dbo.class2 b ON a.student=b.student
完全外连接将确保您从两个表中获取所有数据(匹配 + a.non 匹配 + b.non 匹配)。
你很接近,但我认为这就是你要找的。它们在不同表中的事实对 CASE 来说并不重要,只是 JOIN:
SELECT *,
Case WHEN class1.student = 'ted' THEN 'ted'
ELSE class2.student='ted'
END as ISOK
FROM class1
join class2 on class1.student = class2.student
如果您想查看某个学生是否在 table 中,请使用 exists
。我认为这样的东西会有用:
select (case when exists (select 1 from class1 c1 where c1.name = 'Ted')
then 'class1'
when exists (select 1 from class2 c2 where c2.name = 'Ted')
then 'class2'
end) as which_table
如果名称不在 table 中,则值为 NULL
。
我有一个 table,我想搜索列中是否有值。如果它不存在,我想在另一个 table 中搜索它。 我试过了:
SELECT *,
CASE(WHEN student = 'ted' THEN 'ted'
ELSE ( SELECT student
FROM dbo.class2
WHERE student= 'ted')) END AS ISOK
from dbo.class1
因此,如果 dbo.class1.student
不是 'ted',则 ISOK
列将从 dbo.class2.student
中获取值。
尽管上面的查询是错误的,因为它 returns 更多值。
我很确定我尝试做的方法是错误的。
你能试试这个吗?
SELECT
NVL(a.student, b.student) ISOK
FROM dbo.class1 a
FULL OUTER JOIN dbo.class2 b ON a.student=b.student
完全外连接将确保您从两个表中获取所有数据(匹配 + a.non 匹配 + b.non 匹配)。
你很接近,但我认为这就是你要找的。它们在不同表中的事实对 CASE 来说并不重要,只是 JOIN:
SELECT *,
Case WHEN class1.student = 'ted' THEN 'ted'
ELSE class2.student='ted'
END as ISOK
FROM class1
join class2 on class1.student = class2.student
如果您想查看某个学生是否在 table 中,请使用 exists
。我认为这样的东西会有用:
select (case when exists (select 1 from class1 c1 where c1.name = 'Ted')
then 'class1'
when exists (select 1 from class2 c2 where c2.name = 'Ted')
then 'class2'
end) as which_table
如果名称不在 table 中,则值为 NULL
。