sql - SQL 选择查询根据子表中的特定条件仅返回 1 行
问题描述
根据子表中存在的值,我无法确定如何返回特定的父数据行。
我要应用两个过滤器或某些 case 语句,根据子表中的值返回我的registration_id
from 。table1
- 返回
regestration_id
同时Table3
具有和的type
值。在这种情况下,它应该返回.1
3
registration_id
123
- 返回
regestration_id
whenTable3
仅有type
值 of1
和type
of3
不存在。在这种情况下,它应该返回registration_id
.321
这是我用来连接表的 SQL:
select registration_id from table1 t1
left join table2 t2 on t2.registration_id=t1.registration_id
left join table3 t3 on t3.x_person_id=t2.x_person_id;
解决方案
你可以使用EXISTS
:
select t1.registration_id
from table1 t1
inner join table2 t2
on t2.registration_id=t1.registration_id
WHERE EXISTS(
SELECT 1
FROM table3 t3
WHERE t3.type = 1
AND t3.x_person_id = t2.x_person_id
)
AND EXISTS(
SELECT 1
FROM table3 t3
WHERE t3.type = 3
AND t3.x_person_id = t2.x_person_id
);
和NOT EXISTS
:
select t1.registration_id
from table1 t1
inner join table2 t2
on t2.registration_id=t1.registration_id
WHERE EXISTS(
SELECT 1
FROM table3 t3
WHERE t3.type = 1
AND t3.x_person_id = t2.x_person_id
)
AND NOT EXISTS(
SELECT 1
FROM table3 t3
WHERE t3.type = 3
AND t3.x_person_id = t2.x_person_id
);
如果您想一次性完成,EXISTS
那么:
select t1.registration_id
from table1 t1
inner join table2 t2
on t2.registration_id=t1.registration_id
WHERE EXISTS(
SELECT 1
FROM table3 t3
WHERE t3.type IN (1, 3)
AND t3.x_person_id = t2.x_person_id
HAVING COUNT(DISTINCT t3.type) = 2
)
和:
select t1.registration_id
from table1 t1
inner join table2 t2
on t2.registration_id=t1.registration_id
WHERE EXISTS(
SELECT 1
FROM table3 t3
WHERE t3.type IN (1, 3)
AND t3.x_person_id = t2.x_person_id
HAVING COUNT(CASE t3.type WHEN 1 THEN 1 END) > 0
AND COUNT(CASE t3.type WHEN 3 THEN 1 END) = 0
)
推荐阅读
- android - 为classytaxi 的android 应用内购买部署后端服务器?
- r - 有没有办法在 R Shiny 中显示 .gif 文件?
- pytorch - 当批次大小不是 train_size 的一个因素时,将 loss().item 乘以 batch_size 以获得批次的损失是一个好主意吗?
- android - Android Studio 的模拟器没有启动
- python - 如何解决这个“pip install mysqlclient”错误?
- python - 检查浮点数是否相等时无限循环
- r - 函数中的变量“....”是什么?
- javascript - 如何解决浮点数计算
- python - socket.gaierror:[Errno 10047] getaddrinfo 失败
- mysql - Kafka Connect JDBC Sink Connector 给 WorkerSinkTask ERROR