0

I'm hacking together my first ruby script to read and write to/from mysql.

I want to know if a certain record exists. I have tried:

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

but when I print the class of should_alert, it is a MySQL::STMT rather than a True or False class, or even a 0/1.

What am I missing here? Is a prepared statement even the right thing to use for this?

4

2 回答 2

1
sql = "SELECT IF( EXISTS(SELECT * FROM UserTrucks WHERE User = ? AND Truck = ?), 1, 0)"
于 2012-07-23T08:44:03.710 回答
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" 
于 2012-07-22T16:05:08.210 回答