根据另一行的内容从其他行获取数据

时间:2012-12-07 20:34:41

标签: mysql

我有一个数据表,可能如下所示。答案总是以6块的形式从用户处提交。如果有人对questionID 1回答“1”,那么我需要知道他们为问题4回答了什么,或者如果他们对问题2回答1,那么我需要他们对问题5的回答,如果他们对问题3回答1,我需要他们回答问题6。

user   questionID    response
1      1             2
1      2             3
1      3             1
1      4             5
1      5             5
1      6             2
2      1             1
2      2             6
2      3             3
2      4             3
2      5             2
2      6             5

我真的能在这方面提供一些帮助。非常感谢

2 个答案:

答案 0 :(得分:0)

这是你需要的吗?尝试运行此查询。

select u1.*, u2.response from users u1
left join users u2
on u1.user = u2.user and u1.questionID = u2.questionID - 3
where u1.response = 1

substring('inp1'FROM 4)给出1:

select u1.*, u2.response from users u1
left join users u2
on u1.user = u2.user and
  substring(u1.questionID FROM 4) = substring(u2.questionID FROM 4) - 3
where u1.response = 1

答案 1 :(得分:0)

我认为你想要一个“支点”,在那里你可以得到所有答案:

select
  t1.response as response1,
  t2.response as response2,
  t3.response as response3,
  t4.response as response4,
  t5.response as response5,
  t6.response as response6
from mytable t1
left join mytable t2 on t1.user = t2.user and t2.questionId = 2
left join mytable t3 on t1.user = t3.user and t3.questionId = 3
left join mytable t4 on t1.user = t4.user and t4.questionId = 4
left join mytable t5 on t1.user = t5.user and t5.questionId = 5
left join mytable t6 on t1.user = t6.user and t6.questionId = 6
where t1.user = ?

我会将此视图添加为t1.user作为列,然后您可以从视图中选择user = ?.