题解 | #根据指定记录是否存在输出不同情况#
根据指定记录是否存在输出不同情况
https://www.nowcoder.com/practice/f72d3fc27dc14f3aae76ee9823ccca6b
EXISTS 和 IN 都是在 SQL 查询中使用的条件子句,但它们的用法和作用是不同的。
- EXISTS: EXISTS 用于检查一个子查询是否返回了至少一行结果。它通常与主查询中的条件一起使用,如果子查询返回了至少一行,则主查询中的条件将被满足。EXISTS 不关心子查询返回的具体数据,只关心是否有数据存在。通常在需要检查是否存在相关数据时使用。
示例:
SELECT customer_name FROM customers WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.customer_id);
- IN: IN 用于比较一个表达式是否在一个值的列表中。它可以与单个列的多个值进行比较,如果表达式的值与列表中的任何一个值匹配,则条件为真。IN 比较的是具体的值,而不是查询结果。通常在需要从固定值列表中筛选数据时使用。
示例:
SELECT product_name FROM products WHERE product_id IN (101, 102, 103);
在选择使用 EXISTS 还是 IN 时,考虑你的需求。如果你只关心是否存在相关数据,使用 EXISTS。如果你需要比较一个列的值是否匹配固定的值列表,使用 IN。
with
t_tag_count as (
select
uid,
level,
count(start_time) - count(submit_time) as incomplete_cnt,
round(
ifnull (1 - count(submit_time) / count(start_time), 0),
3
) as incomplete_rate,
count(start_time) as total_cnt
from
exam_record
right join user_info using (uid)
group by
uid
)
select
uid,
incomplete_cnt,
incomplete_rate
from
t_tag_count
where
exists (
select
uid
from
t_tag_count
where
level = 0
and incomplete_cnt > 2
)
and level = 0
union all
select
uid,
incomplete_cnt,
incomplete_rate
from
t_tag_count
where
not exists (
select
uid
from
t_tag_count
where
level = 0
and incomplete_cnt > 2
)
and total_cnt > 0
order by
incomplete_rate
查看4道真题和解析