Mysql将行转换为列并通过响应进行分组。

时间:2014-10-31 15:49:05

标签: mysql

我有4个不同的表用于从用户收集信息,我尝试编写查询以简化输出,以便可以将响应全部视为一行。 这些表的设置如下:

调查

+-----+-----------+
| sID | sTitle    |
+-----+-----------+
| 1   | Survey 1  |
| 2   | Survey 2  |
+-----+-----------+

条目

+-----+-----+
| eID | sID |
+-----+-----+
| 1   | 1   |
| 2   | 1   |
| 3   | 1   |
| 4   | 2   |
| 5   | 2   |
+-----+-----+

问题

+-----+-----+------+------------+
| qID | sID | type | question   |
+-----+-----+------+------------+
| 1   | 1   | text | question A |
| 2   | 1   | text | question B |
| 3   | 2   | text | remark A   |
| 4   | 2   | text | remark B   |
+-----+-----+------+------------+

参赛作品回复

+-----+-----+-----+-------------+
| rID | eID | qID | response    |
+-----+-----+-----+-------------+
| 1   | 1   | 1   | yes         |
| 2   | 1   | 2   | no          |
| 3   | 2   | 1   | maybe       |
| 4   | 2   | 2   | no          |
| 5   | 3   | 1   | foo         |
| 6   | 3   | 2   | bar         |
| 7   | 4   | 3   | answer      |
| 8   | 4   | 4   | unicorns    |
+-----+-----+-----+-------------+
etc...

我希望有一个查询显示它们:

+-----+----------+-----+------------+------------+
| sID | sTitle   | eID | question A | question B |
+-----+----------+-----+------------+------------+
| 1   | Survey 1 | 1   | yes        | no         |
| 1   | Survey 1 | 2   | maybe      | no         |
| 1   | Survey 1 | 3   | foo        | bar        |
+-----+----------+-----+------------+------------+

AND / OR

+-----+----------+-----+------------+------------+
| sID | sTitle   | eID | remark A   | remark B   |
+-----+----------+-----+------------+------------+
| 2   | Survey 2 | 4   | answer     | unicorns   |
+-----+----------+-----+------------+------------+

取决于所查询的调查,因为这将是限制因素。从本质上讲,我想让所有回复调查的人和他们对问题的答案根据调查情况有所不同。让每个调查询问的问题都是列标题,答案就在行中。

我目前正在进行一些长时间的加入和查询以获得每个问题的每个回复,并手动将其添加到一行,因此我希望有更好的方法可以做到这一点它

0 个答案:

没有答案