我看到 SELECT EXISTS
的用法很像:
if db.query("""
SELECT EXISTS (
SELECT 1 FROM checkout
WHERE checkout_id = %s
)
""" % checkout_id).getresult()[0][0] == 't':
对比我喜欢什么:
if db.query("""
SELECT 1 FROM checkout
WHERE checkout_id = %s
LIMIT 1
""" % checkout_id).getresult():
首选哪个,为什么?
附言我正在使用 Python 和 PosgreSQL。
cert=> explain SELECT EXISTS (SELECT 1 FROM checkout WHERE checkout_id = 3);
QUERY PLAN
--------------------------------------------------------------------------------------
Result (cost=4.03..4.03 rows=1 width=0)
InitPlan
-> Index Scan using checkout_pkey on checkout (cost=0.00..4.03 rows=1 width=0)
Index Cond: (checkout_id = 3)
(4 rows)
cert=> explain SELECT 1 FROM checkout WHERE checkout_id = 3 limit 1;
QUERY PLAN
------------------------------------------------------------------------------------
Limit (cost=0.00..4.03 rows=1 width=0)
-> Index Scan using checkout_pkey on checkout (cost=0.00..4.03 rows=1 width=0)
Index Cond: (checkout_id = 3)
(3 rows)
我的意思是,为什么要从结果中获取一行并检查它的第一列是否为真,如果我可以检查是否有任何行,意思相同吗?
最佳答案
在我看来,第二个语句是有问题的,因为如果不满足条件,它不会返回一行。
关于python - 选择存在与限制 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10598935/