我有4個表:SQL與動態字段
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個模板(抽象,內容,author_bio,摘要)。當輸出列的確切數量會變化時,如何編寫一個將一列轉換爲多列(基於同一行中但另一列中的值)的語句?同樣,考慮到輸出列的數量會有所不同,我該如何編寫一個將一列轉換爲多列標題的語句?
http://stackoverflow.com/questions/649802/how-to-pivot-a-mysql-entity-attribute-value-schema就是一個例子。您正在尋找PIVOT行到列 – dash 2011-12-25 21:40:55
適當的[示例代碼](http://sscce.org/)(這裏是SQL語句)比任何ad hoc模式和示例數據格式更有用。請使用'CREATE TABLE'和'INSERT ... VALUES'作爲樣本。期望的結果不需要作爲示例代碼呈現。 – outis 2011-12-25 22:48:08
我編輯的問題 – gandil 2011-12-26 13:58:59