那么检查一行是否存在的最佳方法是什么? EXISTS,COUNT还是num_rows?

时间:2012-01-29 11:52:38

标签: php mysql

如果你唯一的目标是检查php (真或假)中是否存在行,那么最好的方法是什么?

选项1?

$result = mysql_query("SELECT * FROM users WHERE id = '1'");
$num_rows = mysql_num_rows($result);

if ($num_rows == 1) 
    // one user, like it should be.

else 
  // do something else

选项2?

$query = mysql_query("select count(1) from users where id = 1")

if (mysql_result($query, 0) == 1)
    // one user, like it should be.

else 
  // do something else

选项3?

$query = mysql_query("something like SELECT EXISTS( SELECT */1/COUNT(*)/etc. ...)")

if (mysql_result($query, 0) == 1)
    // one user, like it should be.

else 
  // do something else

Beter选项4?

你说出来。

子问题

  • COUNT(*), COUNT(1) or COUNT(id)

3 个答案:

答案 0 :(得分:5)

如果您使用MySQL,选项3是检查行是否存在的最快方法:

$query = mysql_query("SELECT EXISTS(SELECT 1 FROM users WHERE id = 1)")

if (mysql_result($query, 0) == 1)
    // one user, like it should be.

else 
  // do something else

答案 1 :(得分:3)

我认为问题更多的是代码本身,然后是涉及的时间,所以使用他的查询:

$result = mysql_query("SELECT * FROM users WHERE id = '1'");
//if result not returned(false) from Mysql return False Else True
//This is just example and you can do anything you need in side the if()
if(!$result) {
//or return some error or redirect to another piece of code
return FALSE;
} else {
//or do some other php/mysql magic
//if there is a result you have the row to work with of needed
return TRUE;
}
  

<强>的mysql_query
   ...摘自PHP手册返回值

     

对于SELECT,SHOW,DESCRIBE,EXPLAIN和其他语句返回   resultset,mysql_query()在成功时返回资源,或者返回FALSE   错误。

     

对于其他类型的SQL语句,INSERT,UPDATE,DELETE,DROP等,   mysql_query()成功时返回TRUE,错误时返回FALSE。

答案 2 :(得分:1)

EXISTSSELECT COUNT(*)快,因为子查询会在找到一行时停止搜索。它不需要找到它们并计算它们。它将返回0或1:

SELECT EXISTS 
       ( SELECT * FROM ... )