我有一个文章网站,我有一个建议框,我建议阅读更多的文章。我想做的是建议最相关的quizz,而不是挑选随机文章并展示它们。 因此,让我们假设读者正在写一个id为19的文章。在建议框中,我想要显示那些也读过第19号文章的人阅读的文章。如果A人阅读19,26,30和B人正在阅读19,因此他最倾向于在第26,30号文章中提出异议。 我有一张表,我用他的用户ID记录用户阅读的每篇文章。
ID / USER ID / ARTICLEID
1 / 30 / 10
2 / 20 / 10
3 / 20 / 80
4 / 10 / 10
5 / 20 / 60
6 / 10 / 60
7 / 20 / 80
8 / 10 / 90
这是想要的:获取用户当前正在阅读的文章的ID - >转到数据库并获取阅读本文的所有用户的ID - >获取这些用户阅读的所有文章的ID - >按用户数量排序。 这真是令人沮丧,因为我没有太多的mysql经验。所以选择的基本命令似乎不起作用,我正在寻求帮助或只是想法,我会寻求执行它们。 更新1:需要输出
答案 0 :(得分:1)
完整查询
SELECT count(`art_id`) as cnt, `art_id`
FROM user_art
WHERE `user_id` in (
SELECT DISTINCT `user_id`
FROM user_art
WHERE `art_id` = 10 -- Current Article ID to find other user
AND user_id <> 20 -- Current User Id to exclude from list
)
GROUP by `art_id`
ORDER BY cnt DESC , `art_id` DESC
LIMIT 1;
一步一步
输入数据
mysql> SELECT * FROM user_art;
+----+---------+--------+
| id | user_id | art_id |
+----+---------+--------+
| 1 | 10 | 10 |
| 2 | 20 | 30 |
| 3 | 20 | 80 |
| 4 | 10 | 90 |
| 5 | 20 | 10 |
| 6 | 23 | 10 |
| 7 | 23 | 11 |
| 8 | 23 | 12 |
| 9 | 10 | 11 |
+----+---------+--------+
9 rows in set (0,00 sec)
mysql>
查找同时阅读sam文章的所有用户ID
mysql> select DISTINCT `user_id`
-> FROM user_art
-> WHERE `art_id` = 10 -- Current Article ID to find other user
-> AND user_id <> 20; -- Current User Id to exclude from list
+---------+
| user_id |
+---------+
| 10 |
| 23 |
+---------+
2 rows in set (0,00 sec)
mysql>
查找按用户列表阅读的所有文章
查找用户列表读取的所有文章,并按用户desc和文章ID的数量排序desc =&gt;更高的文章_no =&gt;较新的文章
mysql> SELECT count(`art_id`) as cnt, `art_id`
-> FROM user_art
-> WHERE `user_id` in (10,23)
-> GROUP by `art_id`
-> ORDER BY cnt DESC , `art_id` DESC
-> ;
+-----+--------+
| cnt | art_id |
+-----+--------+
| 2 | 11 |
| 2 | 10 |
| 1 | 90 |
| 1 | 12 |
+-----+--------+
4 rows in set (0,00 sec)
mysql>
两个查询的组合
将两个查询与LIMIT联合起来只获取下一篇文章
mysql> SELECT count(`art_id`) as cnt, `art_id`
-> FROM user_art
-> WHERE `user_id` in (
-> SELECT DISTINCT `user_id`
-> FROM user_art
-> WHERE `art_id` = 10 -- Current Article ID to find other user
-> AND user_id <> 20 -- Current User Id to exclude from list
-> )
-> GROUP by `art_id`
-> ORDER BY cnt DESC , `art_id` DESC
-> LIMIT 1;
+-----+--------+
| cnt | art_id |
+-----+--------+
| 2 | 11 |
+-----+--------+
1 row in set (0,00 sec)
mysql>