0

I have the following tables:

Fans

id, id_page, number_of_fans, created_at

This table has many same id_page but it differs in created_at

Page

id, id_facebook, id_keyword, is_processed (0/1)

keyword

id, keyword, category

I am experimenting/trying sub-queries but I didn't get the result that I wanted, sometimes the query is very slow because of its complexity.

I would like the result to:

  1. I will get the latest(created_at) - (returns only 1 row from table fans per page) - number_of_fans in fans table by page and get the sum of all number_of_fans by group by keyword
  2. I will get all the pages group by keyword
  3. I will get all the pages group by keyword where is_processed = 1

How will it be possible to combine the result of 1, 2, 3 with just 1 query in MySQL?

Thank you.

Regards, bhadz

4

1 回答 1

0

You're looking for the groupwise maximum from the Fans table: it can be found from grouping the table by page and selecting the maximum created_at value, this is then joined back to the Fans table to obtain the other columns from that maximum record:

SELECT   Keyword.keyword,
         SUM(Fans.number_of_fans) fans_of_all_pages,
         SUM(IF(Page.is_processed,Fans.number_of_fans,0)) fans_of_processed_pages
FROM     Fans NATURAL JOIN (
           SELECT   id_page, MAX(created_at) AS created_at
           FROM     Fans
           GROUP BY id_page
         ) t
    JOIN Page    ON    Page.id = Fans.id_page
    JOIN Keyword ON Keyword.id = Page.id_keyword
GROUP BY Keyword.id
于 2012-09-02T18:48:38.053 回答