PDA

View Full Version : Resolved Any way to combine these simple queries?


abduraooft
08-12-2009, 02:45 PM
Hi all,

I've a query Select group_id,count(message_id) as thread_count from message
where group_id in (1,2) group by group_id which returns +----------+--------------+
| group_id | thread_count |
+----------+--------------+
| 1 | 11 |
| 2 | 25 |
+----------+--------------+

My intention is to update the column thread_count in the table `group` based on the above result. Is it possible to write a single query to achieve this rather than writing a PHP code to loop through the results of the above query and generating new UPDATE queries?

I know the following query to update a single row update `group` set thread_count=(select count(message_id) from message where group_id=1 )
where group_id=1, but is it possible to extend this query to met the condition where group_id in (1,2) ?

Got it :)
UPDATE `group` as G set G.thread_count=
(
SELECT count( message_id )
FROM message
WHERE
group_id = G.group_id

GROUP BY group_id
)
WHERE G.group_id
IN (1,2)

Thanks.