选择以选择同时查看页面的用户

时间:2010-01-29 03:24:16

标签: sql mysql database select

我有一个表记录每个用户的页面浏览量:

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| view_id      | int(11)      | NO   | PRI | NULL    | auto_increment | 
| page_id      | int(11)      | YES  | MUL | NULL    |                | 
| user_id      | int(11)      | YES  | MUL | NULL    |                | 
+--------------+--------------+------+-----+---------+----------------+

对于每对用户,我想生成他们看过多少页的计数。

我根本不知道该怎么做。 :)我正在使用mysql,以防它具有非标准功能,使这变得轻而易举。

4 个答案:

答案 0 :(得分:3)

select u1.user_id, u2.user_id, count(distinct u1.page_id) as NumPages
from logtable u1
  join
  logtable u2
  on u1.page_id = u2.page_id
  and u1.user_id < u2.user_id /* This avoids counting pairs twice */
group by u1.user_id, u2.user_id;

但你应该考虑过滤一下......

(编辑上面放u1.page_id,原来只是page_id,这对我来说真的很糟糕)

答案 1 :(得分:2)

SELECT DISTINCT page_id
FROM logtable
WHERE user_id = 1 OR user_id = 2
GROUP BY page_id
HAVING COUNT(DISTINCT user_id) = 2

此表返回他们都看过的所有页面。如果你想要计数,那么只需将它作为子查询并计算行数。

SELECT COUNT(*) FROM (the query above) s;

更新,让我们为所有用户对执行此操作。

SELECT u1.user_id, u2.user_id, COUNT(DISTINCT u1.page_id)
FROM logtable u1, logtable u2
WHERE u1.user_id < u2.user_id
  AND u1.page_id = u2.page_id
GROUP BY u1.user_id, u2.user_id

答案 2 :(得分:0)

select a.user_id as user1, b.user_id as user2, count(distinct a.page_id) as views
from yourtable a, yourtable b
where a.page_id = b.page_id 
and a.user_id < b.user_id
group by a.user_id, b.user_id

yourtable更改为您的表名..

答案 3 :(得分:0)

对于users_ids 100和200。

SELECT
  page_id
FROM table1
WHERE user_id IN (100, 200)
GROUP BY page_id
HAVING MAX(CASE WHEN user_id = 100 THEN 1 ELSE 0 END) = 1
  AND MAX(CASE WHEN user_id = 200 THEN 1 ELSE 0 END) = 1;