答案 0 :(得分: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'
答案 1 :(得分:0)
此查询会将您的数据行转换为您的问题数据的别名为Question name
的列
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;