我有一个包含三列的SQLite数据库表:order_id,item,quantity。每行都有一个order_id,一个项目和一个数量。
我正在尝试编写一个查找包含两个不同项(item1和item2)的订单的查询,以便我的输出看起来像这样:
order_id | item | quantity
---------------------------
1234 | item1 | 7
---------------------------
1234 | item2 | 2
---------------------------
5678 | item1 | 5
---------------------------
5678 | item2 | 3
这是我到目前为止拼凑的代码:
cur.execute("SELECT * FROM Orders WHERE term=? AND term=?", [("item1"), ("item2")])
如果我使用OR
语句,我会得到我期望的结果。我逻辑上理解为什么这不适用于AND
,但是我无法弄清楚能使它工作的SQL语句。
答案 0 :(得分:2)
您需要在Order
上内联两个order_id
表:
sql = '''SELECT o1.*, o2.*
FROM Orders as o1
INNER JOIN Orders as o2
ON o1.order_id = o2.order_id
WHERE o1.item = ?
AND o2.item = ?'''
args = ("item1", "item2")
cur.execute(sql, args)
答案 1 :(得分:0)
如果您想要所有包含item1和item2的订单,那么您需要自我加入和输出尝试
Select * From (
select * from sometable I1
inner join someTable i2 on I1.Order_Id = I2.Order_ID
Where I1.item = 'item1' and I2.Item = 'item2'
union
select * from sometable I2
inner join someTable i1 on I2.Order_Id = I1.Order_ID
Where I2.item = 'item2' and I1.Item = 'item1'
) both
order by Order_id,item, quantity desc
答案 2 :(得分:0)
这是另一种方法,使用count子查询和内连接。
# setup
import sqlite3
cnxn = sqlite3.connect(':memory:')
cursor = cnxn.cursor()
cursor.execute("CREATE TABLE Orders (order_id integer, item text, quantity integer)")
cursor.executemany("""
INSERT INTO Orders (order_id, item, quantity)
VALUES (?, ?, ?)
""", [(1234, 'item1', 7), (1234, 'item2', 4), (4567, 'item1', 3)])
# answer
cursor.execute("""
SELECT Orders.order_id, Orders.item, Orders.quantity
FROM Orders
INNER JOIN (SELECT order_id, COUNT(order_id) AS cnt FROM Orders GROUP BY order_id) Orders_count
ON Orders.order_id = Orders_count.order_id
WHERE Orders_count.cnt > 1
""")
results = cursor.fetchall()
# [(1234, u'item1', 7), (1234, u'item2', 4)]
cnxn.close()