如何从 table 中的列等于一个值但不应等于另一个值的 SELECT 记录?

How to SELECT record from a table where column is equal to a value but shouldn't be equal to another value?

我列出了针对给定问题的两种不同解决方案。有没有更好的方法来解决这些类型的问题?

Q: GIVEN EMPLOYEE TABLE 下面,SELECT name which id = 1 but not = 3

-- ID   NAME
-- 1    ram
-- 2    shayam
-- 1    mohan
-- 7    mohan
-- 4    monu
-- 3    monu
-- 1    monu
-- 5    sonu
-- 1    sonu
-- 2    sonu


-- OUTPUT
-- mohan
-- ram
-- sonu

-- Solution 1:
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE e1.id = 1 AND e1.NAME NOT IN (
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE  e2.id = 3);

-- Solution 2:
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE e1.id = 1 
MINUS
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE  e2.id = 3;

-- Use this code to test the logic:
CREATE TABLE EMPLOYEE( id INT, name VARCHAR(25) ); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'ram'); 
INSERT INTO EMPLOYEE(id, name) VALUES(2, 'shayam'); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'mohan'); 
INSERT INTO EMPLOYEE(id, name) VALUES(7, 'mohan'); 
INSERT INTO EMPLOYEE(id, name) VALUES(4, 'monu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(3, 'monu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'monu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(5, 'sonu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'sonu');
INSERT INTO EMPLOYEE(id, name) VALUES(2, 'sonu');

SELECT * FROM EMPLOYEE;

minus 可以,但您不需要 select distinctMinus 是一个集合函数,只有 returns 个不同的行。我倾向于为此使用聚合:

select e.name
from employee e
where id in (1, 3)
group by e.name
having max(id) = 1;   -- there is no 3 if the max is 1

但是,您的方法基本上没问题,尽管我会重复说 select distincts 不是必需的。