0

Fiddle 的架构

结果是:我想获取 msr_name 为“PRE”或“POST”或两者的记录

id  |  msr_name1(only pre)   |  msr_data1(only pre)  |  msr_name2(only post)   |  msr_data2(only post)

16703      PRE                            pre_data                              POST                              post_data

16711      PRE                            pre_data                              NULL                              NULL

16715      NULL                            NULL                                 POST                              post_data
4

1 回答 1

1
SELECT a.id AS id, 
       b.msr_name AS msr_name1, b.msr_data AS msr_data1,
       c.msr_name AS msr_name2, c.msr_data AS msr_data2
FROM (SELECT DISTINCT id FROM Students WHERE msr_name IN ('PRE', 'POST')) AS a
LEFT JOIN Students AS b ON (a.id=b.id AND b.msr_name = 'PRE')
LEFT JOIN Students AS c ON (a.id=c.id AND c.msr_name = 'POST');

我的输出是:

+-------+-----------+-----------+-----------+-----------+
| id    | msr_name1 | msr_data1 | msr_name2 | msr_data2 |
+-------+-----------+-----------+-----------+-----------+
| 16703 | PRE       | pre_data  | POST      | post_data |
| 16711 | PRE       | pre_data  | NULL      | NULL      |
| 16715 | NULL      | NULL      | POST      | post_data |
+-------+-----------+-----------+-----------+-----------+

SQL 小提琴演示

于 2013-03-06T06:13:51.710 回答