Bluehost.com Web Hosting $6.95

UPDATE with GROUP BY

This is a discussion on UPDATE with GROUP BY within the MySQL Database forums, part of the Database Forums category; hi, consider tables 1. blogs (id, num_article) 2. articles (id, blog_id) is it possible to perform the query in the ...


Go Back   Usenet Forums > Database Forums > MySQL Database

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 09-19-2006
howachen@gmail.com
 
Posts: n/a
Default UPDATE with GROUP BY

hi,


consider tables

1. blogs (id, num_article)
2. articles (id, blog_id)

is it possible to perform the query in the following statement?

update blogs, articles set blogs.num_article = count(*) where blogs.id
= articles.blog_id group by articles.blog_id

thanks.

Reply With Quote
  #2 (permalink)  
Old 09-20-2006
Captain Paralytic
 
Posts: n/a
Default Re: UPDATE with GROUP BY


howachen@gmail.com wrote:
> hi,
>
>
> consider tables
>
> 1. blogs (id, num_article)
> 2. articles (id, blog_id)
>
> is it possible to perform the query in the following statement?
>
> update blogs, articles set blogs.num_article = count(*) where blogs.id
> = articles.blog_id group by articles.blog_id
>
> thanks.


This'll do it:

UPDATE blogs,
(
SELECT blog_id, count( * ) AS ac
FROM articles
GROUP BY blog_id
) AS t1
SET blogs.num_article = t1.ac WHERE blogs.id = t1.blog_id

Reply With Quote
  #3 (permalink)  
Old 09-20-2006
Bill Karwin
 
Posts: n/a
Default Re: UPDATE with GROUP BY

howachen@gmail.com wrote:
> update blogs, articles set blogs.num_article = count(*) where blogs.id
> = articles.blog_id group by articles.blog_id


No, there is no support for performing GROUP BY or aggregate
calculations in an UPDATE statement. You can use a subquery if you have
MySQL 4.1 or higher:

update blogs set blogs.num_article = (select count(*) from articles
where blogs.id = articles.blog_id);

Note that it's unnecessary to GROUP BY the column in this case, since
the subquery is calculated for each row of the blogs table, and so it is
naturally for exactly one value of blog_id in each iteration.

Another option is to do the update incrementally, instead of calculating
the count():

update blogs set num_articles = 0;

update blogs, articles
set blogs.num_article = blogs.num_article + 1
where blogs.id = articles.blog_id

This should get the same result.

Regards,
Bill K.
Reply With Quote
Reply
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On




All times are GMT +1. The time now is 01:33 PM.


Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.0.0