简体   繁体   中英

MySQL fastest way to query rows

My problem is that i don't yet have a good server to test this on but i'd like to know if it faster to use:

$sqlgetg = "SELECT assignments.id FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";

or

$sqlgetg = "SELECT NULL FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";

Since i have to check if there even is an assigment for the user with assignment id of x? I don't need anything else but this: if(mysqli_num_rows($resultgetg) > 0) ? In both cases phpMyAdmin gave me the row number that i wanted. (I checked it with without WHERE and it still worked.)

EDIT: I don't know how and why NULL works but it does...

You can select any static value "from" a table if you just want to count the rows returned... SELECT NULL or SELECT 42 or whatever. But both of your strategies are in fact suboptimal, because they require unnecessary work by the server and unnecessary network traffic and unnecessary handling of the result set that you are only planning to discard.

If counting rows is what you want, then actually do that . you should SELECT COUNT(*) AS how_many_rows ... and let the server count the rows and return a single row with a single column ("how_many_rows" -- make up your own alias) containing the count.

I've tested this on my localhost on my i7-4720HQ laptop with samsung EVO 850. Using WAMP-stack, phpMyAdmin and for testing the query

$starttime = microtime(true);

$sqlgetg = "SELECT userassignments.id FROM userassignments";
$resultg = mysqli_query($db, $sqlgetg);

$endtime = microtime(true);
$duration = $endtime - $starttime;

echo $duration;

(PHP script found in here !)

The results for table with 20'000 rows and 5 columns shows the average speed of 0.00021sec seconds with assignments.id and 0.00020sec with NULL... So even if i had 100'000'000 rows the difference would have been just shy of 0.1sec.

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