我正在将每个用户的产品视图记录在数据库表中。
product_id | user_id
--------------------
1 | 1
3 | 1
2 | 1
4 | 1
...
1 | 2
3 | 2
2 | 2
...
1 | 3
3 | 3
5 | 3
目标是:对于给定的产品,返回按频率排序的“已查看客户”的4种产品的列表。因此,对于产品1,应该先出现产品3,因为它被查看过的次数最多(三)达3次。
我想形成一个查询,该查询将通过以下方式为我提供给定产品ID的数据:
product_id | viewed_with_id | frequency_viewed_together
-------------------------------------------------------
1 | 3 | 3
1 | 2 | 2
1 | 4 | 1
1 | 5 | 1
总结:
我当前的查询是:
SELECT u.product_id,u.user_id, p.product_id
FROM also_viewed u
JOIN also_viewed p ON u.user_id = p.user_id
WHERE u.product_id = 1
AND p.product_id != 1
这显示查看过产品1的用户查看过的其他产品,但未按频率对产品进行分组。我会继续尝试。
这是表的转储:
CREATE TABLE `also_viewed` (
`id` mediumint(9) NOT NULL,
`product_id` mediumint(9) UNSIGNED NOT NULL,
`user_id` int(11) UNSIGNED NOT NULL,
`updated_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `also_viewed` (`id`, `product_id`, `user_id`, `updated_at`) VALUES
(1, 1, 1, NULL),
(2, 2, 1, NULL),
(3, 3, 1, NULL),
(4, 4, 1, NULL),
(5, 1, 2, NULL),
(6, 3, 2, NULL),
(7, 2, 2, NULL),
(8, 1, 3, NULL),
(9, 3, 3, NULL),
(10, 5, 3, NULL);
答案 0 :(得分:-1)
http://sqlfiddle.com/#!9/93e37d/9
SELECT DISTINCT u.product_id, p.product_id, COUNT(p.product_id) idx
FROM also_viewed u
JOIN also_viewed p
ON p.product_id != u.product_id
WHERE u.product_id = 1
GROUP BY u.user_id, u.product_id, p.product_id
ORDER BY idx DESC