从平面数据集

时间:2015-12-29 22:40:53

标签: mysql sql stored-procedures

由于现有的数据库架构设计不好,我必须以特殊的方式编写一个select语句,如this thread所示。

SELECT MAX(CASE WHEN Name = 'C' THEN RelativePath END) AS C,
   MAX(CASE WHEN Name = 'CC' THEN RelativePath END) AS CC,
   MAX(CASE WHEN Name = 'S' THEN RelativePath END) AS S,
   MAX(CASE WHEN Name = 'SC' THEN RelativePath END) AS SC,
   MAX(CASE WHEN Name = 'R' THEN RelativePath END) AS R,
   MAX(CASE WHEN Name = 'RC' THEN RelativePath END) AS RC
FROM myTable
WHERE ID = pId;

现在,我需要将其输出与其父表的select语句的输出相连接。父子表的结构如下:

Parent
-------------------
id    -> the primary key
third_party_id
createdBy
createdDate
...

Child
-------------------
id -> the primary key of its Parent table
Name 
...

对于给定的id,我期望的select语句的输出结果类似于以下内容:

third_party_id, createdBy, createdDate, C, CC, S, SC, R, RC

子表可能没有给定父表键的条目。我使用左连接的select语句,但无法获得所需的结果。数据库是mySQL。

如果单个select语句不起作用,如何构造输出的存储过程?

1 个答案:

答案 0 :(得分:0)

SELECT
  Parent.third_party_id,
  Parent.createdBy,
  Parent.createdDate,
  Child.C,
  Child.CC,
  Child.S,
  Child.SC,
  Child.R,
  Child.RC
FROM
  Parent
LEFT OUTER JOIN
(
  SELECT 
     ID,
     MAX(CASE WHEN Name = 'C' THEN RelativePath END) AS C,
     MAX(CASE WHEN Name = 'CC' THEN RelativePath END) AS CC,
     MAX(CASE WHEN Name = 'S' THEN RelativePath END) AS S,
     MAX(CASE WHEN Name = 'SC' THEN RelativePath END) AS SC,
     MAX(CASE WHEN Name = 'R' THEN RelativePath END) AS R,
     MAX(CASE WHEN Name = 'RC' THEN RelativePath END) AS RC
  FROM myTable
  GROUP BY ID
) Child ON
  Child.ID = Parent.ID
WHERE
  Parent.ID = pId;