MySQL:将不同的值连接为单个值

时间:2012-09-18 16:53:31

标签: mysql sql

在mysql db表中,我有与域表有一对多关系的项目,如

项目

----------------
proId | domainId
----------------
  1        1
  1        2
  2        1
  3        3

---------------------
domainId | domainName
---------------------
    1        Web
    2        Mobile
    3        iPhone

我查询

SELECT p.*, d.* FROM projects p LEFT JOIN domain d ON p.domainId = d.domainId

结果

结果

-----------------------------
proId | domainId | domainName
-----------------------------
  1       1          Web
  1       2          Mobile
  2       1          Web
  3       3          iPhone

但是是否可以将所有域显示为单个值,并将其连接到某些内容,例如

-----------------------------
proId | domainId | domainName
-----------------------------
  1       1, 2    Web, Mobile
  2       1       Web
  3       3       iPhone

3 个答案:

答案 0 :(得分:1)

可能您正在寻找 GROUP_CONCAT 功能。

SELECT  a.proID,
        GROUP_CONCAT(b.domainID) domainId,
        GROUP_CONCAT(b.domainName) domainName
FROM    projects a
        LEFT JOIN domain b
            ON a.domainID = b.domainID
GROUP BY a.proID

SQLFiddle Demo

答案 1 :(得分:1)

对于快速提问我现在只是通过朋友的帮助发布了主要观点,并解决了这个问题。现在我发布完整的DB Schema&查询。

<强>模式

CREATE TABLE projects
    (`projectId` int, `projectName` varchar(20))
;

INSERT INTO projects
    (`projectId`, `projectName`)
VALUES
    (1, 'P1'),
    (2, 'P2'),
    (3, 'P3')
;

CREATE TABLE domain
    (`domainId` int, `domainName` varchar(6))
;

INSERT INTO domain
    (`domainId`, `domainName`)
VALUES
    (1, 'Web'),
    (2, 'Mobile'),
    (3, 'iPhone')
;

CREATE TABLE prodomain
    (`domainId` int, `projectId` int)
;

INSERT INTO prodomain
    (`domainId`, `projectId`)
VALUES
    (1, 1),
    (1, 1),
    (3, 2),
        (2, 3)
;

<强>查询

    SELECT p.projectId as proId, projectName, d.*, 
GROUP_CONCAT(d.domainId separator ', ') as all_domains_id, 
GROUP_CONCAT(d.domainName separator ', ') as all_domains_name 
FROM projects p 
    LEFT JOIN projectdomains pd ON p.projectId = pd.projectId
    LEFT JOIN domains d ON d.domainId = pd.domainId
    GROUP BY p.projectId

答案 2 :(得分:0)

SELECT 
    p.proId, 
    group_concat(d.domainId) as domainId, 
    group_concat(d.domainName) as domainName 
FROM 
    projects p 
    inner JOIN 
    domain d ON p.domainId = d.domainId
group by p.proId
order by p.proId