以上是我要解决的问题。首先,我想尝试在SQL中使用EXCEPT子句,并获取Orders表中不存在的所有值。我正在尝试的是:(暂时忽略列名和内容,我只想测试EXCEPT逻辑)
SELECT Id, Name FROM Customers
EXCEPT
SELECT O.CustomerId as Id, C.Name AS Name FROM Customers C , Orders O
WHERE C.Id = O.CustomerId
但是,我在LeetCode上收到此错误,我不确定:
Line 3: SyntaxError: near 'SELECT O.CustomerID as Id, C.Name AS Name FROM Customers C , Orders O WHERE C.Id'
我要从编写的查询中获得的预期输出是:
Id Name
2 Henry
4 Max
编辑:这是LeetCode的问题,在查看使用的版本后,我发现它是mysql-server 5.7.21
答案 0 :(得分:1)
如果您坚持使用EXCEPT
,请设置为EXCEPT ALL
:
SELECT Id FROM Customers
EXCEPT ALL
SELECT CustomerID FROM Orders;
但是我宁愿使用LEFT JOIN / .. IS NULL
:
SELECT C.*
FROM Customers C
LEFT JOIN Orders O ON O.CustomerId = C.Id
WHERE O.CustomerId IS NULL;
请参阅:
答案 1 :(得分:0)
我看到您的dbms是mysql。 Mysql不支持EXCEPT
另一种尝试使用NOT IN
的方法比EXCEPT
容易
模式(MySQL v5.7)
CREATE TABLE Customers(
id int,
Name varchar(50)
);
INSERT INTO Customers VALUES (1,'Joe');
INSERT INTO Customers VALUES (2,'Henry');
INSERT INTO Customers VALUES (3,'Sam');
INSERT INTO Customers VALUES (4,'Max');
CREATE TABLE Orders(
id int,
CustomerId int
);
INSERT INTO Orders VALUES (1,3);
INSERT INTO Orders VALUES (2,1);
查询#1
SELECT Id, Name
FROM Customers
WHERE Id NOT IN (
SELECT O.CustomerID
FROM Orders O
);
| Id | Name |
| --- | ----- |
| 2 | Henry |
| 4 | Max |
如果您的dbms支持EXCEPT
,则我将使用JOIN
而不是,
连接两个表,因为JOIN
连接两个表的语义更清晰。
SELECT Id, Name
FROM Customers
EXCEPT
SELECT O.CustomerID as Id, C.Name AS Name
FROM Customers C JOIN Orders O ON C.Id = O.CustomerID