我的 SQL-EXCEPT-Operator 出了啥问题?
Posted
技术标签:
【中文标题】我的 SQL-EXCEPT-Operator 出了啥问题?【英文标题】:What's wrong with my SQL-EXCEPT-Operator?我的 SQL-EXCEPT-Operator 出了什么问题? 【发布时间】:2018-02-01 16:17:40 【问题描述】:当我从我的表格“Stats”和“Book”中选择“BookID”时,我会分别得到想要的结果:
MariaDB [db1]> SELECT BookID From Book WHERE Author = 'AuthorX';
+--------+
| BookID |
+--------+
| 1003 |
+--------+
MariaDB [db1]> SELECT BookID From Stats WHERE BookID >= 1000;
+--------+
| BookID |
+--------+
| 1010 |
| 1005 |
| 1003 |
+--------+
但是当我尝试使用 EXCEPT 运算符时,我得到一个错误
MariaDB [db1]> (SELECT BookID From Stats WHERE BookID >= 1000)
-> EXCEPT
-> (SELECT BookID From Book WHERE Author = 'AuthorX');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'EXCEPT (SELECT BookID From Book WHERE Author = 'AuthorX')' at line 1
我希望的输出:
+--------+
| BookID |
+--------+
| 1010 |
| 1005 |
+--------+
我做错了什么? 我试过带括号和不带括号,但不知道下一步该尝试什么?
编辑:尝试使用 NOT IN
SELECT BookID From Stats WHERE BookID >= 1000 NOT IN
(SELECT BookID From Book WHERE Author = 'AuthorX');
产量
+--------+
| BookID |
+--------+
| 3 |
| 1010 |
| 1005 |
| 1003 |
+--------+
EDIT2:“AND BookID NOT IN”(除作品外)
仍然很想知道为什么 EXCEPT 没有
EDIT3:https://mariadb.com/kb/en/library/except/ 中的示例确实有效……
EDIT4:MariaDB Vers似乎是是答案。
仍然想知道为什么这些示例有效......
【问题讨论】:
在@MatBaillie 发布的链接中,它说except
是在10.3.0 中引入的。你用的是什么版本?
@kai-dj 我很惊讶你的NOT IN ()
竟然被执行了。应该是AND BookID NOT IN ()
@kai-dj - 将AND BookID
放在它应该在的位置,看看是否可以修复它,目前我什至不知道这意味着什么,更不用说它为什么会执行。 (祝你好运,我今天不在家……)
EXCEPT was introduced in MariaDB 10.3.0.
。这是否回答了仍然很想知道为什么 EXCEPT 没有部分?
@MatBailie 哦耶-抱歉我的头开始受伤了^^
【参考方案1】:
去掉括号。
三行看起来“更好”...
SELECT `BookID` From `Stats` WHERE `BookID` >= 1000
EXCEPT
SELECT `BookID` From `Book` WHERE `Author` = 'AuthorX'
这和你在UNION ALL
看到的差不多...
SELECT BookID From Book WHERE Title LIKE 'Harry Potter%'
UNION ALL
SELECT BookID From Book WHERE Author LIKE '%Toklien%'
编辑:
或者只是尝试另一种表达方式(如果在旧版本的 MariaDB 上)...
SELECT BookID
FROM Book
WHERE BookID >= 1000
AND BookID NOT IN (SELECT BookID
FROM Book
WHERE Author = 'AuthorX'
)
或者……
SELECT BookID
FROM Book
WHERE BookID >= 1000
AND NOT EXISTS (SELECT *
FROM Book lookup
WHERE lookup.Author = 'AuthorX'
AND lookup.BookID = Book.BookID
)
或者……
SELECT
*
FROM
(
SELECT BookID FROM Book WHERE BookID >= 1000
)
high_id
LEFT JOIN
(
SELECT BookID FROM Book WHERE Author = 'AuthorX'
)
target_author
ON target_author.BookID = high_id.BookID
WHERE
target_author.BookID IS NULL
【讨论】:
那么你在某处的另一行还有其他问题...mariadb.com/kb/en/library/except (尝试自行运行;
,然后在最后使用;
再次尝试查询。)
这是唯一的一行……
你试过了吗? (以防万一有其他东西不小心...)
两者都做了——结果相同
只运行前半部分会得到什么(除此之外)?以上是关于我的 SQL-EXCEPT-Operator 出了啥问题?的主要内容,如果未能解决你的问题,请参考以下文章