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.
What's an Explain Plan?
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.
How Do I Generate an Explain Plan?
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.
I've Gots My Explain Plan, But What Does it Mean?!
The MySQL EXPLAIN documentation is a good place to read up on each column that is returned, & what the column represents.