mysql通过有来计数组

发布于 2024-12-11 07:59:14 字数 300 浏览 0 评论 0原文

我有这张表:

Movies (ID, Genre)

一部电影可以有多种类型,因此 ID 并不特定于某个类型,而是多对多的关系。我想要一个查询来查找恰好有 4 种类型的电影总数。我当前的查询是

  SELECT COUNT(*) 
    FROM Movies 
GROUP BY ID 
  HAVING COUNT(Genre) = 4

但是,这会返回 4 的列表而不是总和。如何获取总和而不是 count(*) 列表?

I have this table:

Movies (ID, Genre)

A movie can have multiple genres, so an ID is not specific to a genre, it is a many to many relationship. I want a query to find the total number of movies which have at exactly 4 genres. The current query I have is

  SELECT COUNT(*) 
    FROM Movies 
GROUP BY ID 
  HAVING COUNT(Genre) = 4

However, this returns me a list of 4's instead of the total sum. How do I get the sum total sum instead of a list of count(*)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

多像笑话 2024-12-18 07:59:14

一种方法是使用嵌套查询:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

内部查询获取恰好具有 4 个流派的所有电影,然后外部查询计算内部查询返回的行数。

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

毁梦 2024-12-18 07:59:14
SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t
SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t
爱人如己 2024-12-18 07:59:14

也许

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

虽然这不是所有电影的总和,但有多少电影有 4 种类型。

所以也许你想要

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

Maybe

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total
别在捏我脸啦 2024-12-18 07:59:14

怎么样:

SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a

What about:

SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文