MySQL查询从具有不同行的不同表中获取行到相应的列中

时间:2018-07-19 11:25:11

标签: mysql

我们有两个表格,如下所示:

Table-1 Name: apprecord
---------------------------------------
appid       |  desc            | status
ALT01       |   this is first  | Open
ALT02       |   this is second | Open
ALT03       |   this is third  | Closed
---------------------------------------

Table-2 Name: question
-----------------------------------------------
appid | questionseq |   ques               | ans
ALT01 | 1           | how are you          | good
ALT01 | 2           | are you fine         | yes
ALT02 | 1           | how was your day     | great
ALT02 | 2           | are you coming today | yes
ALT03 | 1           | where are you        | at home
ALT03 | 2           | are you fine         | yes
--------------------------------------------------

如何编写MySQL查询,以便获得如下结果:

----------------------------------------------------------------------------------------
appid | desc          | status| QUES1           |   ANS1   | QUES2                | ANS2
ALT01 | this is first | Open  | how are you     |   good   | are you fine         | yes
ALT02 | this is second| Open  | how was your day|   great  | are you coming today | no
ALT03 | this is third | Closed| where are you   |   at home| are you fine         | yes
---------------------------------------------------------------------------------------

这里QUES1,ANS1,QUES2,ANS2是硬编码/固定的列标题。

1 个答案:

答案 0 :(得分:0)

尝试一下:

样本数据:

create table apprecord(appid varchar(10),desc varchar(100),status varchar(10));
insert into apprecord values
('ALT01','this is first','Open'),
('ALT02','this is second','Open'),
('ALT03','this is third','Closed');
create table question(appid varchar(10),questionseq int,ques varchar(100),ans varchar(10));
insert into question values
('ALT01',1,'how are you','good'),
('ALT01',2,'are you fine','yes'),
('ALT02',1,'how was your day','great'),
('ALT02',2,'are you coming today','yes'),
('ALT03',1,'where are you','at home'),
('ALT03',2,'are you fine','yes');

T-SQL:

select ar.appid,
       `desc`, 
       `status`, 
       q1.ques ques1, 
       q1.ans ans1, 
       q2.ques ques2, 
       q2.ans ans2
from apprecord ar
left join (select appid, ques, ans from question where questionseq = 1) q1
  on ar.appid = q1.appid
left join (select appid, ques, ans from question where questionseq = 2) q2
  on ar.appid = q2.appid

这是标准的透视,尽管它可以使用两个连接来实现上述目的:)