2016-11-16 53 views

回答

0

您可以使用加入

,獲取用戶的Q1值

JOIN `Question` `Q1` 
    ON `Q1`.`user_id` = `User`.`id` 
     AND `Q1`.`question name` = 'Q1' 

,讓您的用戶Q2值

JOIN `Question` `Q2` 
    ON `Q2`.`user_id` = `User`.`id` 
     AND `Q2`.`question name` = 'Q2' 

查詢這個樣子的

SELECT `User`.`id`, 
     `User`.`name`, 
     `Grade`.`grade`, 
     `Q1`.`mark` AS `Q1`, 
     `Q2`.`mark` AS `Q2` 
FROM `User` 
     JOIN `Grade` 
     ON `User`.`id` = `Grade`.`user_id` 
     JOIN `Question` `Q1` 
     ON `Q1`.`user_id` = `User`.`id` 
      AND `Q1`.`question name` = 'Q1' 
     JOIN `Question` `Q2` 
     ON `Q2`.`user_id` = `User`.`id` 
      AND `Q2`.`question name` = 'Q2' 

enter image description here

+0

實際上可以有兩個以上的問題和問題名稱可能會改變 –

+0

@ebinmanuval所以你想要將問題名稱轉換爲列?好吧,等一下 – Beginner

0

這個查詢將您的數據行轉換成這將是別名,你的問題的數據

SET @sql = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'MAX(IF(`Question name` = "', `Question name`, '",`mark`,NULL)) as ', `Question name`) 
) INTO @sql 
FROM Question; 

SET @sql = CONCAT('SELECT `User`.`id`, `User`.`name`, `Grade`.`grade`, ', @sql, ' 
        FROM `User` join `Grade` on `User`.`id` = `Grade`.`user_id` 
        join `Question` on `User`.`id` = `Question`.`user_id` GROUP BY `User`.`id`'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 

User table Grade table Question table Result of the query

SQL Fiddle

相關問題