我的SQL-EXCEPT-Operator出了什么问题?

时间:2018-02-01 16:17:41

标签: sql mysql-error-1064 sql-except

当我选择" BookID"从我的表格"统计"和#34; Book"我得到了理想的结果,如:

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-operator时,我收到错误

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"除了工作

仍然很想知道为什么除了

EDIT3 :来自https://mariadb.com/kb/en/library/except/的示例有效......

EDIT4 :MariaDB Vers< 10.3没有EXCEPT 似乎就是答​​案。

仍然想知道为什么这些例子有用......

1 个答案:

答案 0 :(得分: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