【sql】初识 where EXISTS
文章目录
- 概述
- 1. select 简单示例
- 2. update和DELETE
- 参考
相关文章:
【sql】深入理解 mysql的EXISTS 语法
【sql】初识 where EXISTS
概述
where EXISTS (子查询)多对多中通过中间表查对方列表
1. select 简单示例
用户表A,小组表B,小组和用户是多对多关系,中间有个中间表M
已知 小组 id 即teamId ,想知道这个小组中的用户列表信息,可以如下写sql:
select * from A a where EXISTS (select m.id from M m where a.id = m.aid and m.bid = (参数teamId));
where 后面 跟 exists (子查询)的意思是,括号里面子查询至少有一条记录时,前面的大的select查询语句才返回结果
此查询语句中涉及了三张表:表A ,表B, AB多对多关系表M
【记忆方法:因为要查用户列表,所以外层的大select 查询的from是用户表,然后后面子查询中才是A和B与中间表中的关系条件】
2. update和DELETE
UPDATE TEST_TB01 aa
SET (aa.part_id, aa.flag) =
(SELECT bb.part_id, bb.flag
FROM TEST_TB02 bb
WHERE aa.sensor_id = bb.sensor_id)
WHERE EXISTS
(SELECT 1 FROM TEST_TB02 cc
WHERE aa.sensor_id = cc.sensor_id);
SELECT
aa.sensor_id,aa.part_id,aa.flag
FROM
TEST_TB01 aa
WHERE EXISTS
(SELECT 1 FROM
TEST_TB02 bb
WHERE aa.sensor_id = bb.sensor_id);
SELECT
aa.sensor_id,aa.part_id,aa.flag
FROM
TEST_TB01 aa
WHERE NOT EXISTS
(SELECT 1 FROM
TEST_TB02 bb
WHERE aa.sensor_id = bb.sensor_id);
DELETE FROM
TEST_TB01 aa
WHERE EXISTS
(SELECT 1 FROM
TEST_TB02 bb
WHERE aa.sensor_id = bb.sensor_id);
参考
https://www.cnblogs.com/libin6505/p/8890897.html