MySQL 查询问题

select id from table where id in(20,21,22);

如果表里的id 没有22这行记录,那么我现在只想要22 返回 如何写呢?

阅读 3.2k
5 个回答

数据库原理里面有一种东西叫集合的加减乘除运算. 你这个问题其实就是集合的减法.
PS: 百度搜 MySQL 集合 减法

select id from table where id not in(20,21,22)

想到一个方法比较绕,权当抛砖引玉

SELECT c.i FROM 
  tbl
RIGHT JOIN 
  (SELECT 20 AS i UNION SELECT 21 UNION SELECT 22) AS c
ON tbl.id = c.i
WHERE tbl.id IS NULL;

。。。

select t.id from (
SELECT id FROM table where id in (20,21,22) 
union all select 20 as id
union all select 21 as id
union all select 22 as id
) as t 
group by t.id having count(t.id)=1;

单纯的mysql查询效率会不会太绕?

还有一个方案是:
select id from table where id in(20,21,22);
查到的结果与 20,21,22 进行差集比较.这样的是不是会更快一些?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题