在Python中查询,SQLite 2.6.0,操作错误:near“(”:语法错误

问题描述 投票:0回答:1

我正在尝试查询一个可以回答以下问题的表,但我不明白我的代码中的错误是什么。我是查询新手,所以可能缺少一些简单的东西。

screenshot of error received

print('Q1: Find the name of the sailor who reserved all boats')
print('Your answer should include (sname)')

answer = "SELECT S.sname FROM Sailor S WHERE NOT EXISTS((SELECT B.bid FROM Boat B) EXCEPT (SELECT R.bid FROM Reserve R WHERE R.sid = S.sid))"

t = cur.execute(answer)
names = list(map(lambda x: x[0], t.description))
print(names)
print('--------------------')
for row in t : print(row)
print('--------------------')

我尝试弄乱调试器指出的括号,但错误仍然存在于同一行代码中。我期待一张能回答问题的水手姓名表,或者一张空表。

python sql sqlite syntax operationalerror
1个回答
0
投票

那篇文章详细介绍了执行此操作的经典方法。但我觉得这样更直观一点。

基本上获取水手的结果以及他们保留的唯一船只 ID 的数量。如果该数量等于独特船只的总数,您就知道水手保留了所有这些船只。

with distinct_counts_of_boat_reservations as (
    select 
          s.name,
          count(distinct b.bid) as count_distinct_bid
     from sailor s
    inner
     join reserve r
       on s.sid = r.sid
    inner
     join boat b
       on r.bid = b.bid
    group
       by s.name)
select distinct
       name
  from distinct_counts_of_boat_reservations 
 where count_distinct_bid = (
         select count(distinct bid) 
           from boat)
© www.soinside.com 2019 - 2024. All rights reserved.