mySQL - 为不同的用户

时间:2016-04-29 15:53:04

标签: mysql subquery

我有一个表 ReadingList ,它由几列组成。为简单起见,我们称之为:

  • reading_id
  • link_id_fk
  • user_id_fk

reading_id只是 AI 键。 link_id_fk可以多次存在(对于每个user_id_fk

我正在尝试做的是找到大多数用户存储的前10个 link_id_fk值。

这是我的垃圾尝试(我刚回来了145,我不知道它在哪里得到那个数字 - 但它肯定不是我期待的数字:))

SELECT
  *,
  (SELECT COUNT(*)
   FROM ReadingList
   WHERE link_id_fk = ReadingList.link_id_fk) AS total_saves
FROM
  ReadingList
WHERE
  user_id_fk IN ('test123', 'test2') AND
  link_id_fk > 0 AND deleted = 0;

所需的示例输出为:

link_id_fk   total_saves 
12            3 
34            2 
56            1
78            1

有人能指出我正确的方向吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在子查询中使用GROUP BY

SELECT rl2.link_id_fk, rl2.nb_link
FROM (
  SELECT link_id_fk, count(*) as nb_link
  FROM ReadingList
  WHERE
    user_id_fk IN ('test123','test2')
    AND link_id_fk > 0 
    AND deleted = 0
  GROUP BY link_id_fk
) as rl2
ORDER BY rl2.nb_link DESC
LIMIT 10;