0

我想加入两个 MySQL 表processID并得到后续报告作为报告。

table 1: LMProcess
------------------------------------
| ProcessID | LMNo | Status | Dept | 
------------------------------------
|1          |1001  |1       |Legal |
|2          |1001  |1       |R&D   |
|3          |1001  |1       |D&R   |
|4          |1001  |1       |L&M   |
|5          |1002  |1       |Legal |
|6          |1002  |1       |R&D   |
|7          |1002  |1       |D&R   |
|8          |1002  |1       |L&M   |
------------------------------------

table 2: Recommendation
-----------------------------------
| ID | ProcessID | Recommendation |
-----------------------------------
|    |1          |Yes             |
|    |2          |No              |
|    |3          |Yes             |
|    |4          |Yes             |
|    |5          |Yes             |
|    |6          |No              |
|    |7          |No              |
|    |8          |Yes             |
-----------------------------------

Report: LM File Recommendations by the Departments
----------------------------------
| LMNo | Legal | R&D | D&R | L&M |
----------------------------------
|1001  |Yes    |No   |Yes  |Yes  |
|1002  |Yes    |No   |No   |Yes  |
----------------------------------
4

1 回答 1

1

您正在尝试执行枢轴操作,这是其他一些 RDBMS 本身支持但 MySQL 不支持的操作(因为开发人员认为它真正属于表示层,而不是数据库)。

但是,您可以将结果分组LMNo并使用 MySQL 的GROUP_CONCAT()函数来实现所需的结果:

SELECT   LMNo
       , GROUP_CONCAT(IF(Dept='Legal', Recommendation, NULL)) AS `Legal`
       , GROUP_CONCAT(IF(Dept='R&D'  , Recommendation, NULL)) AS `R&D`
       , GROUP_CONCAT(IF(Dept='D&R'  , Recommendation, NULL)) AS `D&R`
       , GROUP_CONCAT(IF(Dept='L&M'  , Recommendation, NULL)) AS `L&M`
FROM     LMProcess JOIN Recommendation USING (ProcessID)
GROUP BY LMNo
于 2012-07-23T18:23:36.923 回答