Trying to figure out if I can reduce my mysql queries to decrease the amount of connections to the database. Is their away to pull all the rows and then just count a certain row where is matches a certain string such as:
mysql_query(
"SELECT *, (COUNT(unread = 1) AS msgsunread)
FROM message_received WHERE user_id = '$uid'");
You’re on the right track. If you extend the count statement in your example into a full subquery, you’ll get:
Which’ll have the unread count you’re looking for (in every row!). MySQL should be smart enough to cache the result of that count query, too, so you’ve effectively performed two queries over one connection.
Having the count tagged onto every row does seem a bit excessive, though… Maybe this is a place where two queries is just a better bet – and you can try to optimize elsewhere with joins, or something else that MySQL is less of a nuisance about – counts are a pain in the dominant buttock.
Hope this helps!
PS: If this is PHP, you should be able to perform any number of queries over a single connection – just call
mysql_query(...)a bunch of times before callingmysql_close(...).