Re: MySQL Speed




Ridge Burner wrote:
Can someone tell me which of these 2 SQL queries will be more efficient? I'm
having a debate with another guy about which would be less resource
intensive for MySQL.

The first uses MySQL to pick a random row in a single statement:
<?php
$sql = "SELECT FROM myTable ORDER BY RAND() LIMIT 1";
$query = mysql_query($sql,$conn);
?>


The second does the same thing, but uses 2 queries to do it:
<?php
$sqlA = "SELECT COUNT(id) FROM myTable";
$queryA = mysql_query($sqlA,$conn);
$num = mysql_result($queryA,0,0);
$random = rand(1,$num);
$sqlB = "SELECT FROM myTable WHERE id='" . $random . "' LIMIT 1";
?>

Basically, which approach would be better to use in a high traffic
environment to retrieve a single random row?

The problem here is that the second query is wrong for what you're
trying to do. The number of rows in a table doesn't necessarily have
anything kind of relationship with the primary keys. Rows could have
been deleted or the seed value of the auto-increment column might not
have been 1.

.



Relevant Pages

  • Re: MySQL Speed
    ... The first uses MySQL to pick a random row in a single statement: ... The problem here is that the second query is wrong for what you're ...
    (comp.lang.php)
  • Re: MySQL Speed
    ... The first uses MySQL to pick a random row in a single statement: ... The second does the same thing, but uses 2 queries to do it: ...
    (comp.lang.php)
  • How to use a value from a pick list?
    ... a second query is run using the site as the ... Any help for this mysql, php, htlm noob. ... I'll be able to move forward with more interesting and complex code. ...
    (comp.lang.php)
  • Re: Using a query on a query (or view)
    ... > In my php page I'm using a mysql database. ... then run a second query on the results returned from the first query. ...
    (comp.lang.php)
  • Re: Using a query on a query (or view)
    ... > In my php page I'm using a mysql database. ... then run a second query on the results returned from the first query. ...
    (alt.php)