1

在 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
4

3 回答 3

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 演示

于 2012-09-18T16:55:50.583 回答
1

对于快速问题,我现在刚刚发布了要点,因为在朋友的帮助下它已经解决了,现在我发布了完整的 DB Schema & Query。

架构

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
于 2012-09-18T17:25:39.937 回答
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
于 2012-09-18T17:00:11.507 回答