python - 选择存在与限制 1

标签 python sql postgresql

我看到 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/

相关文章:

python - 我如何连接一列QTableWidget

python - 绘制来自 Pandas 的某些数据点

python - Django:python manage.py migrate 什么都不做

sql - 具有多个更新的SQL Server事务,插入

ruby-on-rails - Rails 迁移 -- rake db :status says migration is down, 但数据库已经迁移?

java - 数据库中的编码问题

python - Django 表单重新验证空/空白字段

sql - 检测保存在 SQLite 表中的\n 字符?

php - Mysqli准备语句(SQL注入(inject)预防)

PostgreSQL - 让两个事务同时运行