首页 > MySQL 查询问题

MySQL 查询问题

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

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


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


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

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 id from table where id not in(20,21,22)


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

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


。。。

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;
【热门文章】
【热门文章】