如何在sql中使用3个连接显示此输出

时间:2017-12-25 18:11:17

标签: sql database oracle

SQL>从Art_Object中选择*;

    ID YEAR                      TITLE                     DES                       A_NAME
     1 1890                      Old Man                   An old man in the dark    van Gogh
     2 1894                      Cat                       White cat in black canvas van Gogh
     3 1853                      Monalisa                  Smiling woman             Leonardo
     4 1888                      The meeting               Two men talking           Picaso
     5 2017                      The crimson stone         Group of characters       Omar

SQL>从绘画中选择*;

    ID PAINT_TYPE                     MATERIAL                       STYLE
     2 Oil Painting                   Oil                            Cubism
     3 Satin                          Paint                          Expressionism

SQL>从雕塑中选择*;

    ID MATERIAL                           HEIGHT     WEIGHT STYLE
     4 Mud                                   172        180 Cubism

SQL> select * from other;

    ID TYPE                           STYLE
     1 3D painting                    Realist
     5 Digital Painting               Manga

SQL>

查询说(博物馆里最古老的艺术品的类型是什么?)所以我想我需要加入这4张桌子并显示最小年份,即#34; int"这里有(绘画中的paint_type或来自Sculpture的Material或来自Other的Type),在输出中显示(类型)和(年)

2 个答案:

答案 0 :(得分:1)

以下是解决此问题的传统方法:

select ao.*,
       (case when exists (select 1 from painting p where p.id = ao.id) then 'painting'
             when exists (select 1 from sculpture s where s.id = ao.id) then 'sculpture'
             when exists (select 1 from other o where o.id = ao.id) then 'other'
        end) as art_type             
from art_object ao
order by year, id
fetch first one row only;

并非所有数据库都支持fetch first;但是,所有人都有办法实现这一目标。

此外,如果绑定了多个对象,则只返回最旧的一个。

编辑:

在Oracle 12之前的版本中,你可以这样做:

select ao.*,
       (case when exists (select 1 from painting p where p.id = ao.id) then 'painting'
             when exists (select 1 from sculpture s where s.id = ao.id) then 'sculpture'
             when exists (select 1 from other o where o.id = ao.id) then 'other'
        end) as art_type             
from (select ao.*, rownum as seqnum
      from art_object ao
      order by ao.year desc
     ) ao
where seqnum = 1;

答案 1 :(得分:0)

你是对的,就像这样:

SELECT
  o1.A_Name,
  o1.Year,
  p.Paint_type,
  s.MATERIAL, s.HEIGHT, s.WEIGHTSTYLE,
  o.TYPE,o.STYLE
FROM Art_Object as o1
INNER JOIN
(
   SELECT ID, MIN(Year) AS Oldest
   FROM Art_Object 
   GROUP BY ID
) AS o2 ON o1.ID = o2.ID AND o1.Year = o2.Oldest
INNER JOIN painting as p ON o1.ID = p.ID
INNER JOIN sculpture AS s ON o1.ID = s.ID
INNER JOIN other as o ON o1.ID = o.ID