可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.