自定义查询从MySQL检索所需数据

时间:2016-04-29 23:44:43

标签: mysql mysqli

我正在创建一个事件创建(人们可以参加)系统,并且为事件创建表单是动态的(不同输入的数量等)我将每个与会者插入到同一个表中。

表格如下:

| id  | event_id | question      | answer          | paid | shown |
| 123 |      174 | enimi         | mati            | NULL | jah   |
| 124 |      174 | pnimi         | kask            | NULL | jah   |
| 125 |      174 | mail          | m@kask.com      | NULL | jah   |
| 126 |      174 | enimi         | kati            | NULL | jah   |
| 127 |      174 | pnimi         | kuusk           | NULL | jah   |
| 128 |      174 | mail          | k@kuusk.com     | NULL | jah   |
| 129 |      174 | enimi         | tiina           | NULL | jah   |
| 130 |      174 | pnimi         | lepp            | NULL | jah   |
| 131 |      174 | mail          | t@lepp.com      | NULL | jah   |
+-----+----------+---------------+-----------------+------+-------+

我有什么方法可以将这些信息作为:

|event_id|enimi|pnimi|mail        |paid|
|174     |mati |kask | m@kask.com |null|

祝你好运, WK

1 个答案:

答案 0 :(得分:1)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id  INT NOT NULL PRIMARY KEY
,event_id INT NOT NULL
,question      VARCHAR(12) NOT NULL
,answer          VARCHAR(12) NOT NULL
,paid INT NULL
,shown VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(123 ,174 ,'enimi','mati'      ,NULL,'jah'),
(124 ,174 ,'pnimi','kask'      ,NULL,'jah'),
(125 ,174 ,'mail','m@kask.com' ,NULL,'jah'),
(126 ,174 ,'enimi','kati'      ,NULL,'jah'),
(127 ,174 ,'pnimi','kuusk'     ,NULL,'jah'),
(128 ,174 ,'mail','k@kuusk.com',NULL,'jah'),
(129 ,174 ,'enimi','tiina'     ,NULL,'jah'),
(130 ,174 ,'pnimi','lepp'      ,NULL,'jah'),
(131 ,174 ,'mail','t@lepp.com' ,NULL,'jah');

SELECT x.event_id
     , MAX(CASE WHEN x.question = 'enimi' THEN x.answer END) enimi
     , MAX(CASE WHEN x.question = 'pnimi' THEN x.answer END) pnimi
     , MAX(CASE WHEN x.question = 'mail' THEN x.answer END) mail
     , paid
  FROM my_table x
  JOIN 
     ( SELECT event_id
            , question
            , MIN(id) id 
         FROM my_table 
        GROUP 
           BY event_id
            , question
     ) y 
    ON y.id = x.id
 GROUP 
    BY event_id;

+----------+-------+-------+------------+------+
| event_id | enimi | pnimi | mail       | paid |
+----------+-------+-------+------------+------+
|      174 | mati  | kask  | m@kask.com | NULL |
+----------+-------+-------+------------+------+