1

I have 3 tables as follows
1) Tag_master

  id        tag_name
------------------------------
  1         Movies
  2         English Movies

2) Tags

   Tag_id          article
----------------------------------
     1               ABC
     2               ABC
     1               XYZ
     1               PQR
     2               EFG
     1               EFG
     2               LMN
     2               HIJ 
 --------------------------------

3)article_view

     article          view_date
  --------------------------------
       ABC            2015-07-01
       ABC            2015-07-01
       ABC            2015-07-02
       ABC            2015-07-03
       XYZ            2015-07-05
       XYZ            2015-07-05
       XYZ            2015-07-08
       PQR            2015-08-01
       PQR            2015-08-01
       LMN            2015-08-02
       HIJ            2015-08-02
 -----------------------------------

I want to get no of viewers for each article those 'Tag' containing word Movies

My query as follow

 select t.article,count(*) as cnt from tags t LEFT JOIN tag_master tm ON  
  t.tag_id=tm.id INNER JOIN article_view act ON t.article=act.article  
 WHERE tm.tag_name LIKE '%movies%' group by article

it give the following result

  article   cnt
 ----------------   
   ABC       8
   HIJ       1
   LMN       1
   PQR       2
   XYZ       3    
-----------------

In this result article ABC have only 4 viewers but in query result it showing 8

please help me to correct the query

1
  • 2
    Be careful what you count. Also, you have no PK on article_views. This may prove problematic. Commented Sep 3, 2015 at 12:32

2 Answers 2

1

As already pointed out in the comment Be careful what you count so you need to get the count from article_view separately and then join back something as

select 
 t.article,
 act.cnt 
 from tags t 
 LEFT JOIN tag_master tm ON  t.tag_id=tm.id 
 INNER JOIN (
   select count(*) as cnt, article from article_view
   group by article
 )act
 ON t.article=act.article  
 WHERE 
 tm.tag_name LIKE '%movies%' 
 group by article
Sign up to request clarification or add additional context in comments.

1 Comment

Well, not really. Properly, you need a PK on article_views, and then a COUNT of DISTINCT values returned from that table.
1

Why dont you query from article_view table

select article,count(view_date) as cnt from article_view group by article

??

you should count view_date in your query

3 Comments

i need to connect with tag_master because when ever another tag came your query not suit for this
that ok.. Did you try count(t.view_date) in your query
Also you can user inner join instead of left join

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.