Mysql一对多关系数据检索

时间:2012-02-24 10:55:45

标签: mysql

我有像

这样的表格

tbl_biodata:

id     : int           value=>1
name   : varchar(50)        value => mike
...

tbl_biodata_education

第一行---

id         : int    value=>1
biodata_id : foreignkey to tbl_biodata.id   value => 1
level      : varchar(50)    value => bachelor
year       : int(4)     value => 2006

第二行---

id         : int    value=>2
biodata_id : foreignkey to tbl_biodata.id   value => 1
level      : varchar(50)    value => masters
year       : int(4)     value => 2010

我必须导出数据,以便生物数据不会重复多次和所有 来自tbl_biodata_education的重复教育列为2006年学士学位,2010年硕士学位

决赛桌将是:

id
name    => mike
education   =>  bachelor 2006, masters 2010
来自simon-at-mso-net

解决方案

SELECT
        b.id,
        b.name,
        GROUP_CONCAT(be.education) AS education

FROM tbl_biodata b

LEFT JOIN (
    SELECT
        biodata_id,
        CONCAT(level,' ',year) AS education
    FROM tbl_biodata_education
) be
ON b.id = be.biodata_id
GROUP BY b.id

1 个答案:

答案 0 :(得分:1)

GROUP_CONCAT是您的朋友,可以将您需要的条目作为列表获取,每个tbl_biodata record有一个列表。我选择建议使用子查询来简单地从tbl_biodata_education获取数据,以便education字段可以在CONCAT在外部查询中GROUP_CONCAT之前更加干净SELECT b.id, b.name, GROUP_CONCAT(be.education) AS education FROM tbl_biodata b LEFT JOIN ( SELECT biodata_id, CONCAT(level,' ',year) AS education FROM tbl_biodata_education ) be on b.id = be.biodata_id GROUP BY b.id

{{1}}