Postgres脚本更简单

时间:2014-10-01 07:35:42

标签: sql postgresql

我想知道下面是否有更简单的方法来编写查询。简而言之,查询的结果是总结电影泰坦尼克赢得的所有奥斯卡奖,奖项包含在不同的表格中。这个脚本有效但似乎很复杂。

SELECT title, production_year, 
COUNT(*) + (crew.c + director.c + writer.c + actor.c) AS Oscars
FROM movie_award, 
(SELECT COUNT(*) AS c
    FROM crew_award 
    WHERE result = 'won'
    AND title = 'Titanic'
    AND award_name = 'Oscar') AS crew,
(SELECT COUNT(*) AS c
    FROM director_award
    WHERE result = 'won'
    AND title = 'Titanic'
    AND award_name = 'Oscar') AS director,
(SELECT COUNT(*) AS c
    FROM writer_award
    WHERE result = 'won'
    AND title = 'Titanic'
    AND award_name = 'Oscar') AS writer,
(SELECT COUNT(*) AS c
    FROM actor_award
    WHERE result = 'won'
    AND title = 'Titanic'
    AND award_name = 'Oscar') AS actor
WHERE result = 'won'
AND title = 'Titanic'
AND award_name = 'Oscar'
GROUP BY crew.c, director.c, writer.c, actor.c, title, production_year;

1 个答案:

答案 0 :(得分:1)

有点难以在不看模式的情况下给出“按原样运行”的答案,但你应该能够使用UNION ALL来简化某些事情,例如;

SELECT title, production_year, COUNT(*) Oscars
FROM ( 
  SELECT title, production_year, result, award_name FROM movie_award
  UNION ALL
  SELECT title, production_year, result, award_name FROM crew_award
  UNION ALL
  SELECT title, production_year, result, award_name FROM director_award
  UNION ALL
  SELECT title, production_year, result, award_name FROM writer_award
  UNION ALL
  SELECT title, production_year, result, award_name FROM actor_award
)z
WHERE result = 'won' AND title = 'Titanic' AND award_name = 'Oscar'
GROUP BY title, production_year;