COUNT个未返回期望值

时间:2018-10-04 21:53:22

标签: mysql count

给出我的表之间的以下关系:enter image description here

我需要显示只有两个主演演员(例如“第二个星期”)的电影的名字。

SELECT act.cod_film,
(SELECT COUNT(act.cod_film) FROM film, act WHERE act.starring like 
'Seconday' and act.cod_film=film.cod_film) as namecounter
FROM act;

这总是返回具有“第二个”演员的电影,但计数始终是相同的数字。我需要每部电影中“第二个”演员的人数。

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

这将查找具有2位“第二”演员的电影

SELECT act.cod_film
FROM act
GROUP BY act.cod_film
HAVING SUM(CASE WHEN act.starring like = 'Seconday' THEN 1 ELSE O END) = 2

您可以在这样的子查询中使用它(或通过许多其他可能的方式)

SELECT *
FROM FILMS
WHERE cod_film IN (
                  SELECT act.cod_film
                  FROM act
                  GROUP BY act.cod_film
                  HAVING SUM(CASE WHEN act.starring like = 'Seconday' THEN 1 ELSE O END) = 2
                  )

或:您可以在联接中使用这种方式

SELECT *
FROM FILMS
INNER JOIN (
           SELECT act.cod_film, COUNT(*) NUM_OF
           FROM act
           GROUP BY act.cod_film
           HAVING SUM(CASE WHEN act.starring like = 'Seconday' THEN 1 ELSE O END) = 2
           ) A ON FILMS.cod_film = A.cod_film

注意:

  1. like要求使用通配符才能有效,请勿将等号替换为不一样的东西
  2. 如果您希望最少有2个次要演员,则可以像=一样将>=调整为sum(case...) >= 2

答案 1 :(得分:0)

行为表被提及2次,请尝试从select count()中删除行为

  1. 介词1
SELECT act.cod_film,
(SELECT COUNT(act.cod_film) FROM film WHERE act.starring like 
'Seconday' and act.cod_film=film.cod_film) as namecounter
FROM act;
  1. 介词2
SELECT act.cod_film, count(*)
FROM act JOIN film ON (act.act.cod_film = film.cod_film)
WHERE act.starring like 'Seconday'
GROUP BY act.cod_film