我有一个包含客户查看的产品的表,它看起来像这样:
| id | visitor_id | product |
| 1 | 51a474f | 5 |
| 2 | 51a474f | 3 |
| 3 | 51a474f | 3 |
| 4 | 207ed9e | 3 |
| 4 | 207ed9e | 5 |
| 5 | 47d98ee | 4 |
| 6 | 47d98ee | 3 |
| 7 | 47d98ee | 2 |
如果有人访问,例如产品编号5,我想让所有访问过相同产品的访问者然后将所有产品(ID不是5)分组,并按访问次数计算。
我知道我可以使用多个查询来执行此操作,但我认为单个查询会比该解决方案更好。
答案 0 :(得分:0)
从我对你的问题的理解,这是我的答案。我没有测试过数据。
select visitor_id,product, count(visitor_id)
from <your table>
where product=(select product from <your table> where id = (select max(id) from <your table>))
group by product
union
select visitor_id,product, count(visitor_id)
from <your table>
where product not in (select product from <your table> where id = (select max(id) from <your table>))
答案 1 :(得分:0)
我认为您的意思是您希望所有产品(ID不是5)并且由查看否的访问者查看。 5?你可以尝试这样的事情:(就在我的头顶,没有经过测试)
SELECT product, COUNT(id) num
FROM the_table
WHERE
visitor_id IN ( SELECT DISTINCT visitor_id FROM the_table WHERE product='5' AND visitor_id!='this_visitor_id' ) AND
product != '5'
GROUP BY product
ORDER BY num DESC