SQL - 从多个表中选择多个字段

时间:2015-06-09 10:39:14

标签: mysql sql-server oracle-sqldeveloper

想象一下:

表1

ID  Type    Priority
1212    A   CRITICAL
1213    B   MAJOR
1214    B   MINOR
1215    A   MAJOR
1216    A   CRITICAL
1217    A   CRITICAL

表2

ID         STATE        CHANGEDATE
1212       Pending      03-06-2015 17:47
1212       Closed       04-06-2015 05:47
1212       InProgress   03-06-2015 15:32
1212       Start        03-06-2015 15:07
1212       Opened       03-06-2015 13:47
  • table1包含所有ID信息
  • table2包含所有个人ID信息

我需要什么:我需要从两个表中获取所有ID信息。

为什么我会挣扎:除了我的n00b级别(我只是说我还没有Valhalla材料),我无法将第一个表格中的信息与第二个表格相关联。

我想象的是:

ID   Type   Priority    Opened              Closed
1212    A   CRITICAL    03-06-2015 13:47    -
1215    A   MAJOR       06-06-2015 18:00    07-06-2015 18:00
1216    A   CRITICAL    03-05-2015 13:10    04-06-2015 18:00
1217    A   CRITICAL    01-06-2015 11:03    05-06-2015 18:00

更新:

这是我尝试过的,但专注于一个特定的ID(1212):

SELECT
  MAX (ID_A) AS "ID",
  MAX (STATE_A) AS "ACTION NAME",
  MAX (CHANGEDATE_A) AS "START",
  MAX (STATE_B) AS "ACTION NAME",
  MAX (CHANGEDATE_B) AS "END"
FROM (
SELECT
  ID AS ID_A,
  STATE AS STATE_A,
  CHANGEDATE AS CHANGEDATE_A,
  NULL AS ID_B,
  NULL AS STATE_B,
  NULL AS CHANGEDATE_B
FROM table2
WHERE table2.ID = '1212' AND table2.STATE = 'Start'
UNION ALL
SELECT
  NULL AS ID_A,
  NULL AS STATE_A,
  NULL AS CHANGEDATE_A,
  ID AS ID_B,
  STATE AS STATE_B,
  CHANGEDATE AS CHANGEDATE_B
FROM table2
WHERE table2.ID = '1212' AND table2.STATE = 'Close');

运行此项我将得到以下结果:

ID   ACTION NAME    START         ACTION NAME   END
1212    Start   03-06-2015 13:47    Close        -

我需要的是这一点,但这次是针对所有ID,生成一个列表(没有指定ID)。

2 个答案:

答案 0 :(得分:0)

select  t1.ID,
        t1.Type,
        t1.Priority,
        max(case when t2.State = 'Opened' then ChangeDate end) as Opened,       
        max(case when t2.State = 'Closed' then ChangeDate end) as Closed
from    table1 t1 join table2 t2 on t1.id = t2.id
group by t1.ID,
         t1.Type,
         t1.Priority

答案 1 :(得分:0)

您需要在SQL中使用JOIN。这允许您关联此类信息。

基本语法如下。

您在理想的解决方案中引用了OPENED和CLOSED,但由于这不在您的任何一个基表中,我不知道如何计算它。

select t1.ID,  
       t1.Type,    
       t1.Priority,
       t2.CHANGEDATE
FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.REQUESTID