I am writing the following sub query for some project specific purpose:
SELECT count(*) from table1
WHERE userB='$p' AND userA IN
(SELECT userB FROM table1
WHERE userA='$row[username]')
I was curious if this was the best practice when doing it in PHP or should I resort to the conventional way of first getting the subquery result and then counting the records?
I was curious if this was the best practice when doing it in PHP or should I resort to the conventional way of first getting the subquery result and then counting the records?
Leaving the SQL query in PHP or stored procedure holy war aside, less trips to the database is the best practice. There's time to the database & back that can never be recouped, and separating the queries runs the risk of data changing in between the queries.
Can the query itself be optimized? In this example, potentially yes:
SELECT COUNT(*)
FROM TABLE t
JOIN TABLE t2 ON t2.userB = t.userA
AND t2.userA = '$row[username]'
WHERE t.userB = '$p'
If you really want to be sure about query performance, you'll have to get familiar with generating an explain plan & interpreting the output to tune the query.
The MySQL explain plan shows how the MySQL query optimizer has decided to run a SELECT statement in order to best access the data that's been requested.
In MySQL, you just have to add the keyword explain to the SELECT query, before the SELECT
keyword. IE:
EXPLAIN SELECT COUNT(*)
FROM TABLE t
JOIN TABLE t2 ON t2.userB = t.userA
AND t2.userA = '$row[username]'
WHERE t.userB = '$p'
Probably should have mentioned this earlier, but you don't want to run this from within PHP because it won't return what you queried for. Use whatever SQL IDE, like PHPMyAdmin/etc.
The MySQL EXPLAIN documentation is a good place to read up on each column that is returned, & what the column represents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With