从多个表中有效选择,从另一个表中选择的值

时间:2013-10-15 15:02:39

标签: sql oracle

我想从多个相同构造的表中选择,为每一行返回三列的值,其中一列的值由另一个查询找到。例如,执行此操作的低效方法可能是:

Select Film_Title, Main_Actor, Run_Time From Film_Table_1
  Where Film_Title in
       (Select Film_Title
          From Awesome_Films_Table
          Where Film_Year equals "1984")
UNION ALL
Select Film_Title, Main_Actor, Run_Time From Film_Table_2
  Where Film_Title in
       (Select Film_Title
          From Awesome_Films_Table
          Where Film_Year equals "1984")
Select Film_Title, Main_Actor, Run_Time From Film_Table_3
  Where Film_Title in
       (Select Film_Title
          From Awesome_Films_Table
          Where Film_Year equals "1984")
Select Film_Title, Main_Actor, Run_Time From Film_Table_4
  Where Film_Title in
       (Select Film_Title
          From Awesome_Films_Table
          Where Film_Year equals "1984");

实际上,我有很多'Film_Table_#'可供选择。任何人都可以建议如何更有效地实现这一目标?我认为更换:

Select Film_Title
            From Awesome_Films_Table
            Where Film_Year equals "1984"

我目前在每个Where说明符上都有一个在开始时定义的单个变量可能有帮助,但我不确定如何实现。

1 个答案:

答案 0 :(得分:0)

Oracle中的类似内容:

  1. equals应该是=
  2. “应该是'
  3. 最糟糕的设计是每部电影有一张桌子。理想情况下,在一个集中的表格中,每部电影应该是一行(如果需要,可以去NF) )

    WITH AFT
      AS (SELECT
               FILM_TITLE TITLE
          FROM
               AWESOME_FILMS_TABLE
          WHERE
               FILM_YEAR = '1984')
    SELECT
        FILM_TITLE,
        MAIN_ACTOR,
        RUN_TIME
    FROM
        FILM_TABLE_1,
        AFT
    WHERE
        FILM_TITLE = TITLE
    UNION ALL
    SELECT
        FILM_TITLE,
        MAIN_ACTOR,
        RUN_TIME
    FROM
        FILM_TABLE_2,
        AFT
    WHERE
        FILM_TITLE = TITLE
    UNION ALL
    SELECT
        FILM_TITLE,
        MAIN_ACTOR,
        RUN_TIME
    FROM
        FILM_TABLE_3,
        AFT
    WHERE
        FILM_TITLE = TITLE
    UNION ALL
    SELECT
        FILM_TITLE,
        MAIN_ACTOR,
        RUN_TIME
    FROM
        FILM_TABLE_4,
        AFT
    WHERE
        FILM_TITLE = TITLE;</li>