从MySQL结果中分配BOOL

时间:2012-07-22 15:52:22

标签: mysql ruby boolean prepared-statement exists

我正在攻击我的第一个ruby脚本来读取和写入mysql。

我想知道某条记录是否存在。我试过了:

sql = "SELECT EXISTS(SELECT * FROM UserTrucks WHERE User = ? AND Truck = ?)"
pst = con.prepare(sql)
does_exist = pst.execute(user_id, truck_id)

但是当我打印should_alert类时,它是一个MySQL :: STMT而不是True或False类,甚至是0/1。

我在这里缺少什么?准备好的陈述是否适合用于此目的?

2 个答案:

答案 0 :(得分:1)

sql = "SELECT IF( EXISTS(SELECT * FROM UserTrucks WHERE User = ? AND Truck = ?), 1, 0)"

答案 1 :(得分:0)

为什么不使用计数

sql = "SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS Exist FROM UserTrucks WHERE User = ? AND Truck = ?"

sql = "SELECT CASE WHEN EXISTS(SELECT * FROM UserTrucks WHERE User = ? AND Truck = ?) THEN 1 ELSE 0 END AS Exist"