使用except子句时出错

mgdq6dx1  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(207)


以上是我想解决的问题。首先,我想尝试在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

8yoxcaq7

8yoxcaq71#

我看到你的数据库管理系统是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   |

db fiddle视图
如果您的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
xam8gpfp

xam8gpfp2#

如果你坚持使用 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;

请参见:
选择其他表中不存在的行

相关问题