开发者

mysql query with all columns plus count one certain column

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:

SELECT *,
    (SELECT COUNT(*) FROM message_received WHERE unread = 1 AND user_id = $uid) AS unread_count,
FROM message_recieved WHERE user_id = $uid;

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 calling mysql_close(...).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜