简体   繁体   中英

mysql speed mysql_num_rows vs query limit 1

i had to check if a value (string) is in my database.

at the moment i do a

select a.email,b.vuid from user a, verteiler_user b where a.email=\''.$email.'\' and a.kid='. $kid.' and b.vid='. $vid. ' and a.uid = b.uid

as query with a mysql_num_rows , then check if >=1

But is it faster to do a query with limit 1; ? and check if a row is coming back?

Yes. It would be faster to run a limit 1 query. And if all you're doing is checking for the existence of a row, why bother returning all those columns? Simply select 1 . That will be (negligibly) faster. BTW: Your code looks vulnerable to SQL injection attacks. Consider sanitizing the dynamic parts of your query with mysql_real_escape_string() or a similar function.

LIMIT 1 will have better performance because it will stop matching when the LIMIT has been satisfied.

If you only ever expect 1 row, add LIMIT 1 to your query.

Also, if you are only checking for the presence of that string in the query, there is no need to use column names with SELECT in the query. Just use SELECT 1... .

you could try:

select count(*) from user a, verteiler_user b 
     where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid

and get the count by:

$row=mysql_fetch_array(...);
if ($row[0] > 0)  // is there a hit?
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM