Counting one table of records for matching records of another table

耗尽温柔 提交于 2019-12-08 02:47:18

问题


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

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:

   record_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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/5745686/counting-one-table-of-records-for-matching-records-of-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!