开发者

Counting one table of records for matching records of another table

Hey guys. This is my table of how it works:

Counting one table of records for matching records of another table

I want to be able to count the number of views (the views are unique which contains user's IP), for records that matches record in another table, for example I do a GET request and a SQL query will find matches and count the number of views that have been collected for each record, so it'll display something like this:

GET query: stack

Display:

   reco开发者_运维技巧rd_id    |    keyword    |    total_views
----------------------------------------------------
       2        |     stack     |         2
----------------------------------------------------
       5        |     stack     |         1 

As you can see in the table there are 2 views for record_id 2 and 1 view for record_id 5, and so on. Do you get what I mean? I'm having trouble knowing how to do this.

Cheers.


SELECT  r.*, COUNT(v.record_id)
FROM    records r
LEFT JOIN
        views v
ON      v.record_id = r.record_id
WHERE   r.keyword = 'stack'
GROUP BY
        r.record_id

Create the following indexes:

records (keyword, record_id)
views (record_id)

for this to work fast.


select `record_id`, `keyword`, count(*) as `total_views`
       from `views` join `records` using (`record_id`)
       where `keyword`='stack'
       group by `record_id`
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜