如何检查SELECT EXISTS是否返回值? [英] How to check whether SELECT EXISTS returns a value or not?

查看:106
本文介绍了如何检查SELECT EXISTS是否返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试快速确定user_ID是否是目标"的所有者.我相信我的SQL查询很好,但是我试图找到一种检查结果的好方法!

I am trying to quickly determine if a user_ID is the owner of a 'goal'. I believe my SQL query is good, but I'm trying to find a nice way of checking the result!

在这种情况下,无论我为$ obj_id或$ user_id输入什么,我的函数都将返回true.我认为这是因为mysql_num_rows甚至将错误结果计为一行吗?那么我应该使用哪种PHP代码检查结果是否存在?

In this case, no matter what I put for $obj_id or $user_id, my function returns true. I assume it's because mysql_num_rows is counting even a false result as a row? So what PHP code should I use to check to see if the result exists or not?

请注意,我想要一些简短而精致的东西!我知道我可以做很长的路(检查count(*),返回mysql_assoc然后检查计数值...),但是那很长很长,很丑.

Note that I want something short and elegant! I know I could do it the long way (check count(*), return mysql_assoc then check the count value...) but that is long winded and ugly.

有什么想法吗?谢谢!

$query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";
if (@mysql_num_rows(mysql_query($query))!=1) {
    return false;
} else {
    return true;
}

推荐答案

不要理会EXISTS.内联存在将始终给一个行,其中包含"true"或"false".

Don't bother with EXISTS. The in-line exists will always give one row containing "true" or "false".

您要查找零行"或至少一行",因此将查询更改为类似的内容,然后然后检查返回多少行

You're looking for either "zero rows" or "at least one row" so change the query to something like this and then check how many rows are returned

SELECT 1 FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id' LIMIT 1

这篇关于如何检查SELECT EXISTS是否返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆