使用union时SQL语法错误或缺少数据库("(":语法错误))

时间:2016-02-03 21:51:55

标签: sqlite syntax union

我正在尝试使用union,但我得到了这个模糊的语法错误。我可以让每个查询单独运行,但是当我尝试使用union时,我会收到此错误。

(SELECT s.sname, COUNT(s.sname) AS number
FROM sailor s, boat b
WHERE  b.rating <= s.rating
GROUP BY s.sname)
UNION
(SELECT s.sname, 0 AS number
FROM sailor s
WHERE NOT EXISTS(
              SELECT * FROM boat b
              WHERE s.rating >= b.rating));

1 个答案:

答案 0 :(得分:0)

在SQL中,只有子查询使用括号。在复合查询中,必须在没有它们的情况下编写各个SELECT:

SELECT s.sname, COUNT(s.sname) AS number
FROM sailor s, boat b
WHERE  b.rating <= s.rating
GROUP BY s.sname
UNION
SELECT s.sname, 0 AS number
FROM sailor s
WHERE NOT EXISTS(
              SELECT * FROM boat b
              WHERE s.rating >= b.rating);

在这种特定情况下,您可能只想使用outer join

SELECT s.sname,
       IFNULL(COUNT(b.rating), 0) AS number
FROM sailor AS s
LEFT JOIN boat AS b
ON b.rating <= s.rating;