带动态字段的SQL

时间:2011-12-25 21:36:18

标签: mysql sql dynamic-data

我有4张桌子:

CREATE TABLE Category (
    Id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(255) NOT NULL,
) Engine=InnoDB;

CREATE TABLE Category_Template (
    Id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(255) NOT NULL,
    Category_Id INT UNSIGNED NOT NULL,
    FOREIGN KEY (Category_Id) REFERENCES Category (Id)
) Engine=InnoDB;

CREATE TABLE Post (
    Id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    Post_Name VARCHAR(255) NOT NULL,
    Category_Id INT UNSIGNED NOT NULL,
    FOREIGN KEY (Category_Id) REFERENCES Category (Id)
) Engine=InnoDB;

CREATE TABLE Post_Fields (
    Id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    Post_Id INT UNSIGNED NOT NULL,
    Category_Template_Id INT UNSIGNED NOT NULL,
    Value VARCHAR(255) NOT NULL,
    FOREIGN KEY (Category_Template_Id) REFERENCES Category_Template (Id)
) Engine=InnoDB;

例如,假设有一个属于旅行类别的帖子:

INSERT INTO Category 
(Id, Name) 
  VALUES
(1, 'Where to go?')
;

INSERT INTO Category_Template
(Category_Template_Id, Name,       Category_Id)
  VALUES
(1,                    'Budget',   1),
(2,                    'Location', 1),
(3,                    'Time',     1)
;

INSERT INTO Post
(PostId, Post_Name,        Category_Id)
  VALUES
(1,     'America is good', 1),
(2,     'Hot Travel',      1)
;

INSERT INTO Post_Fields 
(Id, Post_Id, Category_Template_Id, Value)
  VALUES
(1,  1,       1,                    '1000 $'),
(1,  1,       2,                    'New York'),
(1,  1,       3,                    'January 2012'),
(1,  2,       1,                    '2000 $'),
(1,  2,       2,                    'Brasil'),
(1,  2,       3,                    'May 2012')
;

我想运行一个SQL查询,该查询将列出属于给定类别的所有帖子,并将这些帖子的所有字段列为单独的列,类别模板名称为列名。结果应该是这样的:

Post Id     Post_Name         Budget         Location        Time
1           America is good   1000 $         New York        January 2012
2           Hot Travel        2000 $         Brasil          May 2012

我的问题是,不同类别的类别模板具有不同的名称,因此很难编写单个常规用法查询。例如,旅行类别可以有3个模板(位置,预算,时间),而书籍类别有4个模板(抽象,内容,作者,摘要)。当输出列的确切数量发生变化时,如何编写将一列转换为多列的语句(基于同一行但在另一列中的值)?同样,考虑到输出列的数量会有所不同,我如何编写一个将一列转换为多列的语句?

1 个答案:

答案 0 :(得分:2)

SELECT Post_Id as `Post Id`, Post_Name,
    (SELECT Value FROM Post_Fields WHERE Category_Template_Id=1 
          AND Post_Fields.Post_Id=Post.Post_id) AS `Budget`,
    ... more of the same ...
FROM Post WHERE Post_Id = 1