数据透视表在两个表之间水平到垂直的mysql

问题描述 投票:0回答:1

我有一个问答,下面是我的表格结构

从tbl_test_question中选择*;

q_id |   que          | opt1  |   opt2 |   opt3 |   opt4 |   ans
------------------------------------------------------------------
 1   |  what is this? |  cat  |   dog  |   owl  |   cow  |   opt2
 2   |  what is that? |  man  |   pig  |   bat  |   rat  |   opt4
 3   |  who is this?  |  ice  |   flea |   dirt |   lion |   opt1
 4   |  who is that?  |  goat |   meat |   kid  |   gin  |   opt3

从tbl_user_answer中选择*

 uid |   qid |   submit_ans |   correct_ans
-------------------------------------------------
  1  |    1  |     opt2     |       opt2
  1  |    2  |     opt3     |       opt4
  1  |    3  |     opt4     |       opt1 
  1  |    4  |     opt1     |       opt3

同时加入两者,我希望我的结果看起来像这样。

qid  |  submit_ans |  submittext |  correct_ans |  correcttext
-------------------------------------------------------------
 1   |     opt2    |    dog      |     opt2     |     dog             
 2   |     opt3    |    bat      |     opt4     |     rat                  
 3   |     opt4    |   lion      |     opt1     |     ice                  
 4   |     opt1    |   goat      |     opt3     |     kid                  

我还无法想出任何办法使它看起来像这样。我从来没有做过枢轴。是否有可以获取结果的查询?

mysql pivot-table
1个回答
0
投票

您需要连接表并使用CASE表达式,如下所示:

select
  q.q_id qid, u.submit_ans submit_ans,
  case u.submit_ans
    when 'opt1' then q.opt1
    when 'opt2' then q.opt2
    when 'opt3' then q.opt3
    when 'opt4' then q.opt4
  end submit_text,
  u.correct_ans,
    case u.correct_ans
    when 'opt1' then q.opt1
    when 'opt2' then q.opt2
    when 'opt3' then q.opt3
    when 'opt4' then q.opt4
  end correcttext
from tbl_test_question q inner join tbl_user_answer u
on u.qid = q.q_id

请参见demo。结果:

> qid | submit_ans | submit_text | correct_ans | correcttext
> --: | :--------- | :---------- | :---------- | :----------
>   1 | opt2       | dog         | opt2        | dog        
>   2 | opt3       | bat         | opt4        | rat        
>   3 | opt4       | lion        | opt1        | ice        
>   4 | opt1       | goat        | opt3        | kid 
© www.soinside.com 2019 - 2024. All rights reserved.