两个表之间的group_concat

时间:2014-01-24 09:58:54

标签: mysql sql select group-by group-concat

表1: PROJECT_BASIC_INFORMATION

PROJECT_BASIC_INFORMATION_ID | TITLE
PBID_1                         TITLE_1
PBID_2                         TITLE_2
PBID_3                         TITLE_3

表2: MAP_ASSOCIATED_PROJECTS

MAP_ID | PROJECT_BASIC_INFORMATION_ID | ASSOCIATED_PROJECT_BASIC_INFORMATION_ID 
  1            PBID_1                          PBID_2 
  2            PBID_1                          PBID_3

我希望在表1中有一个类似于project_basic_information_id的查询,以逗号分隔的值给出我所有关联的project_basic_information_id和相应的标题。

Ex:对于table1中的PBID_1,我应该得到像

这样的输出
Project_basic_information_ids  | Project_titles 
pbid2,pbid3                      title2,title3

我试过了这个查询

SELECT  GROUP_CONCAT(DISTINCT a.`ASSOCIATED_PROJECT_BASIC_INFORMATION_ID`) AS PROJECT_BASIC_INFORMATION_IDS,GROUP_CONCAT(DISTINCT b.`TITLE`) AS TITLE
FROM MAP_ASSOCIATED_PROJECTS a  LEFT OUTER JOIN
`PROJECT_BASIC_INFORMATION` b ON  b.PROJECT_BASIC_INFORMATION_ID =a.PROJECT_BASIC_INFORMATION_ID 

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT GROUP_CONCAT(DISTINCT a.ASSOCIATED_PROJECT_BASIC_INFORMATION_ID) AS Project_basic_information_ids  ,
       GROUP_CONCAT(DISTINCT b.TITLE) AS Project_titles 
FROM MAP_ASSOCIATED_PROJECTS a  
LEFT OUTER JOIN PROJECT_BASIC_INFORMATION b ON a.ASSOCIATED_PROJECT_BASIC_INFORMATION_ID = b.PROJECT_BASIC_INFORMATION_ID 
WHERE a.PROJECT_BASIC_INFORMATION_ID = 'PBID_1'
GROUP BY a.PROJECT_BASIC_INFORMATION_ID