sql - 查询以检查记录是否存在并且表中的列值是否为空
问题描述
给定一个@InvId
标识Contact
记录的值,然后可以将其连接到UserAccount
记录,例如
select *
from UserAccount UA
join Contact as c on UA.email = C.email and C.type = 'Director'
where C.InvId = @InvId
我正在处理两个需要设置标志变量的场景,@userExits
如果
Users
表中存在匹配的记录,并且该记录中的user_id
值为 NULLUserAccount
。Users
表中不存在匹配的记录
到目前为止,我制定的查询在第二种情况下失败了。
declare @userExits int
if exists (
select 1
from UserAccount UA
join Contact as c on UA.email = C.email and C.type = 'Director'
where C.InvId = @InvId
and exists (
select 1
from Users U
where U.email = UA.email
and UA.user_id is null
)
)
set @userExists = 1
用户表:
user_id | first_name | last_name | email | telephone
---------------------------------------------------------------
10 | John | Doe | jdoe@gmail.com | 123456
11 | Joe | Dane | jdane@gmail.com | 3456789
联系表:
contact_id | inv_id | first_name | last_name | email | type
-------------------------------------------------------------------------
1 | 100 | john | Doe | jdoe@gmail.com | director
用户帐户表:
s_id | first_name | last_name | email | username | user_id
----------------------------------------------------------------------------
1 | john | Doe | jdoe@gmail.com | jdoe@gmail.com | 10
2 | joe | Dane | jdane@gmail.com | jdane@gmail.com | null
任何线索将不胜感激。
解决方案
根据您在评论中的澄清,我认为您想测试以下 2 个条件:
条件一:User
记录存在但user_id
为空
select 1
from UserAccount UA
inner join Contact as C on UA.email = C.email and C.[type] = 'Director'
where C.InvId = @InvId
-- User Record exists
and exists (select 1 from Users U where U.email = UA.email)
-- user_id is null
and UA.[user_id] is null
条件2:User
记录不存在
select 1
from UserAccount UA
inner join Contact as C on UA.email = C.email and C.[type] = 'Director'
where C.InvId = @InvId
-- User Record doesn't exist
and not exists (select 1 from Users U where U.email = UA.email)
这些可以与 a 结合OR
来测试这两个条件,如下所示:
declare @userExists int;
if exists (
select 1
from UserAccount UA
inner join Contact as C on UA.email = C.email and C.[type] = 'Director'
where C.InvId = @InvId
and (
(UA.[user_id] is null and exists (select 1 from Users U where U.email = UA.email))
or not exists (select 1 from Users U where U.email = UA.email)
)
)
begin
set @userExists = 1;
end;
顺便说一句,变量真的应该被调用@userExists
吗?不是@userNotExists
吗?
注意 1:有必要知道然后使用该变量来做什么@userExists
- 例如,如果您使用它来更新记录,那么很可能更新和测试可以组合成一个语句。
注2:我必须假设这仅用于测试目的?因为不推荐使用电子邮件地址加入 - 除非您准备对电子邮件地址设置唯一限制,但有些人仍然共享电子邮件地址。
注意 3:最好的做法是在表格命名中保持一致,以确定您是使用单数形式还是复数形式。你用过Users
(复数)和Contact
(单数)。
推荐阅读
- blazor-server-side - 服务器端 Blazor 偶尔会丢失身份验证状态
- oracle - SSIS 向 Oracle 云 VS-2019 和 MS Oracle 源发送带有数据参数的查询
- javascript - .sort() 不适用于数组(javascript)
- c - 未检索平方根值
- assembly - 为什么当我添加随机浮点指令时,汇编中的这个简单计数循环开始表现异常?
- python - 在 python 中重塑数据框
- php - 如何将我的 SQL 转换为 Laravel Builder
- java - 数据截断:第 1 行的“公司名称”列的数据太长
- python - 熊猫:按组设置差异
- asp.net - Kendo UI for jQuery Excel 导出格式表