2012-12-05 44 views
0

我做下面的查詢查看一個一對多的關係,列標題

SELECT 
     p.id 
     ,q.name 
     ,pa.result 
    FROM 
     postulant_answers as pa 
    LEFT OUTER JOIN postulants as p ON (p.id = pa.postulant_id) 
    LEFT OUTER JOIN questions as q ON (q.id = pa.question_id); 

它告訴我下面的結果:

+------+--------------+--------+ 
    | id | name   | result | 
    +------+--------------+--------+ 
    | 9 | Question 1 |  15 | 
    | 9 | Question 2 |  70 | 
    | 9 | Question 3 |  75 | 
    | 591 | Question 1 |  15 | 
    | 591 | Question 2 |  70 | 
    | 591 | Question 3 |  75 | 

但我需要更多的東西一樣:

+------+------------+------------+------------+ 
    | id | Question 1 | Question 2 | Question 3 | 
    +------+------------+------------+------------+ 
    | 9 |   15 |   70 |   75 | 
    | 591 |   15 |   70 |   75 | 

我可以在一個查詢中做到嗎?
任何幫助,將不勝感激

回答

2

這就是所謂的支點,但MySQL不具有旋轉功能,這樣你就可以實現這個使用聚合函數和CASE

SELECT p.id, 
    max(case when q.name = 'Question 1' then pa.result end) Question1, 
    max(case when q.name = 'Question 2' then pa.result end) Question2, 
    max(case when q.name = 'Question 3' then pa.result end) Question3 
FROM postulant_answers as pa 
LEFT OUTER JOIN postulants as p 
    ON (p.id = pa.postulant_id) 
LEFT OUTER JOIN questions as q 
    ON (q.id = pa.question_id) 
group by p.id 

SQL Fiddle with Demo

結果:

| ID | QUESTION1 | QUESTION2 | QUESTION3 | 
------------------------------------------- 
| 9 |  15 |  70 |  75 | 
| 591 |  15 |  70 |  75 | 

上述工程巨大的,如果你有一個已知的數的問題,但如果問題的數量是未知的,那麼你可以使用一個事先準備好的聲明,與此類似:

SET @sql = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'max(case when q.name = ''', 
     q.name, 
     ''' then pa.result end) AS ', 
     replace(name, ' ', '') 
    ) 
) INTO @sql 
FROM questions; 

SET @sql = CONCAT('SELECT p.id, ', @sql, ' 
        FROM postulant_answers as pa 
        LEFT OUTER JOIN postulants as p 
        ON (p.id = pa.postulant_id) 
        LEFT OUTER JOIN questions as q 
        ON (q.id = pa.question_id) 
        group by p.id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

SQL Fiddle with Demo

+0

http://datacharmer.org/downloads/pivot_tables_mysql_5.pdf這似乎PDF爲您提供很多很好的,易於遵循的選項示例。 –

+0

@bluefeet但是如果我的問題是可變的。我只給了3個例子,但在實際情況下,大約有100個不同的問題,我寧願寫一些產生每個列的東西,而不是寫100次'max(case ...',或者是我唯一的選擇? –

+0

@AlterLagos看到我的編輯,你可以使用一個準備好的語句來動態地生成列表 – Taryn