SQL查询从两个表中进行选择并与第三个表进行比较

时间:2014-10-19 05:00:06

标签: mysql sql oracle

我是sql的新手并尝试执行查询。

我创建了以下表格并且它们正常工作。

create table ACTOR
(
   actor_name varchar(30),
   gender varchar(8),
   date_of_birth date,
   primary key(actor_name)
);

我一直在坚持如何与cast_memeber表进行比较。

 select movie_title as MOVIE_TITLE

2 个答案:

答案 0 :(得分:2)

对于条件计数,您可以将SUM()与表达式一起使用,加入CAST_MEMEBERACTOR表使用COUNT()来计算电影的所有成员,并使用表达式对结果作为布尔值,这样做会根据你的条件给你计数

SELECT 
  m.movie_title,
  m.release_year,
  SUM(a.gender = 'female') no_of_female_members,
  SUM(a.gender = 'male') no_of_male_members,
  COUNT(c.actor_name) no_of_all_members 
FROM
  MOVIE m 
  LEFT JOIN CAST_MEMEBER c 
    ON (m.movie_title = c.movie_title AND m.release_year = c.release_year) 
  JOIN ACTOR a 
    ON (a.actor_name = c.actor_name) 
GROUP BY m.movie_title,m.release_year

答案 1 :(得分:1)

select movie_title,
       release_year,
       count(decode(t.gender,'FEMALE',1)) female_actors
from movie m , (select c.movie_title 
                       a.gender,
                       c.release_year
                from cast_member c, actor a
                where c.movie_title = a.movie_title
                  and c.actor_name = a.actor_name) t
where m.movie_title  = t.movie_title
  and m.release_year = t.release_year
group by m.movie_title ,t.release_year