16.MySQL中的IN 和 NOT IN

IN()只要比较的字段或数据在给定的集合内,那么比较结果就为真,NOT IN()正好与IN()的功能相反。

1.准备

CREATE DATABASE mahaiwuji;
USE mahaiwuji;
CREATE TABLE emp
(
    empno INT PRIMARY KEY,
    ename VARCHAR(10),
    sal INT
);
INSERT INTO emp VALUES (1,'smith',2800);
INSERT INTO emp VALUES (2,'allen',1500);
INSERT INTO emp VALUES (3,'ward',3500);
INSERT INTO emp VALUES (4,'jones',5000);
INSERT INTO emp VALUES (5,'martin',1600);
INSERT INTO emp VALUES (6,'blake',3000);

2.IN

查找sal为1500或3000或5000的信息

SELECT * FROM emp WHERE sal=1500 OR sal=3000 OR sal=5000;
-- 等价于
SELECT * FROM emp WHERE sal IN (1500,3000,5000);
s16_1.png

3.NOT IN

查找sal不是1500也不是3000也不是5000的信息

SELECT * FROM emp WHERE sal!=1500 AND sal!=3000 AND sal<>5000;
-- 等价于
SELECT * FROM emp WHERE sal NOT IN (1500,3000,5000);
s16_2.png

你可能感兴趣的:(16.MySQL中的IN 和 NOT IN)