SQLite check if a row exists

前端 未结 2 1169
说谎
说谎 2021-01-21 11:30

I\'m trying to check if a specific ID exists in a table named \"Products\" in my sqlite database.

def existsCheck( db, id )
    temp = db.execute( \"select exist         


        
相关标签:
2条回答
  • 2021-01-21 12:10

    There is no need to use a subquery:

    def existsCheck( db, id )
        db.execute( "select 1
                     from Products
                     where promoID = ?",
                    [id] ).length > 0
    end
    

    This returns a boolean result.

    0 讨论(0)
  • 2021-01-21 12:16

    Change it to:

    def existsCheck( db, id )
        temp = db.execute( "select 1 where exists(
            select 1
            from Products
            where promoID = ?
        ) ", [id] ).any?
    end
    

    SQL query returns 1 when condition is met or empty result set if it's not. Whole function returns boolean depending on result set.

    0 讨论(0)
提交回复
热议问题