Sqlite查询 - 卡在一个返回循环的查询上

时间:2017-10-07 19:46:19

标签: sql sqlite

我有以下关系模式。

def fib(number):

if number == 0:
    return 0
if number == 1:
    return 1
else:
    number = fib(number - 1) + fib(number - 2)
    return number

user = int(input("Enter a position in the fibonacci sequence: "))

print fib(user)

找到未从乳制品类别订购产品的cutomer的cid。

以下是我的尝试,但是我很遗憾为什么它多次返回每个CID

stores(sid, name, phone, address)
categories(cat, name)
products(pid, name, unit, cat)
carries(sid, pid, qty, uprice)
customers(cid, name, address)
orders(oid, cid, odate, address)
olines(oid, sid, pid, qty, uprice)
deliveries(trackingno, oid, pickUpTime, dropOffTime)

1 个答案:

答案 0 :(得分:2)

乳制品:

SELECT *
FROM products
WHERE cat = 'dai';

含乳制品的订单行:

SELECT *
FROM olines
WHERE pid IN (SELECT pid
              FROM products
              WHERE cat = 'dai');

乳制品订单:

SELECT *
FROM orders
WHERE oid IN (SELECT oid
              FROM olines
              WHERE pid IN (SELECT pid
                            FROM products
                            WHERE cat = 'dai'));

没有任何此类订单的客户:

SELECT cid
FROM customers
WHERE cid NOT IN (SELECT cid
                  FROM orders
                  WHERE oid IN (SELECT oid
                                FROM olines
                                WHERE pid IN (SELECT pid
                                              FROM products
                                              WHERE cat = 'dai')));

如果不允许使用子查询,则可以将三个内部表一起加入,然后使用compound query查找未显示在其中的cid值:

SELECT cid
FROM customers

EXCEPT

SELECT cid
FROM orders
JOIN olines   USING (oid)
JOIN products USING (pid)
WHERE cat = 'dai';