0

我有一个包含客户查看的产品的表格,它看起来像这样:

| 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)进行分组,并按访问次数计算它们。

我知道我可以用多个查询来做到这一点,但我认为单个查询会比那个解决方案更好。

4

2 回答 2

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>))
于 2013-05-28T10:27:03.207 回答
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
于 2013-05-28T10:27:59.390 回答