0

我有一个我试图运行的 SQL 语句,但它抛出了一个错误:

SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp
GROUP BY fp.forum_id
WHERE (
    SELECT COUNT(p.post_id) AS num_joined_posts
    FROM posts p
    WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC')
        AND p.forum_id = fp.forum_id
) > 0
ORDER BY num_posts DESC

forums_posts表是一个将论坛 ID 与帖子 ID 匹配的关系表,并且该posts表(也存储帖子的论坛 ID)仅包含有关每个帖子的信息。我试图找出:哪些论坛有 TypeA、TypeB 或 TypeC 类型的帖子;以及每个论坛中有多少帖子。

嵌套 SQL 语句从来都不是我的强项。有人可以指出正确的方法吗?谢谢。

4

3 回答 3

4

where应该在之前group by

您也可以使用显式来编写join

SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp join
     (SELECT p.forum_id, COUNT(p.post_id) AS num_joined_posts
      FROM posts p
      WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC')
      group by p.forum_id
     ) p
     on p.forum_id = fp.forum_id
GROUP BY fp.forum_id
ORDER BY num_posts DESC

虽然,我认为最有效的演绎可能是:

SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp join
GROUP BY fp.forum_id
having exists (select 1
               FROM posts p
               WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC') and
                     p.forum_id = pf.forum_id
               limit 1
              )
ORDER BY num_posts DESC

特别是如果您对帖子(forum_id,post_type)有索引。我将条件havingwhere子句移到子句,因为分组后用于此比较的数据可能较少。

于 2013-01-08T15:12:07.063 回答
1

尝试这个-

SELECT fp.forum_id, COUNT(fp.forum_id) AS num_posts
FROM forums_posts fp
WHERE (
    SELECT COUNT(p.post_id) AS num_joined_posts
    FROM posts p
    WHERE p.post_type IN ('TypeA', 'TypeB', 'TypeC')
        AND p.forum_id = fp.forum_id
) > 0
GROUP BY fp.forum_id
ORDER BY num_posts DESC
于 2013-01-08T15:13:09.857 回答
0

我就是这样做的,SQL 往往使用连接更快。

SELECT * FROM 
(
  SELECT fp.forum_id,
       SUM(CASE p.post_type = 'TypeA' THEN 1 ELSE 0 END) AS A_Count,
       SUM(CASE p.post_type = 'TypeB' THEN 1 ELSE 0 END) AS B_Count,
       SUM(CASE p.post_type = 'TypeC' THEN 1 ELSE 0 END) AS C_Count
  FROM forums_posts fp
  LEFT JOIN posts p ON fp.forum_id = p.forum_id
  GROUP BY fp.forum_id
) T
WHERE T.A_count > 0 AND T.B_count > 0 AND T.C_count > 0 

我没有测试过这个,所以它可能有错别字。

于 2013-01-08T15:13:38.923 回答