SQLite check if a row exists

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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 exists(         select 1         from Products         where promoID = ?     ) ", [id] ) end 

that's my current code but that returns an array which means I have to deal with conversion before I can use it as a boolean. Any ideas how I can change it so that it returns an int with the value 1?

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!