从EAV中选择将返回两次行

时间:2018-10-26 08:37:58

标签: mysql sql entity-attribute-value

我有下表

contacts
╔═══════════╦═══════════╦══════════╦═══════════╗
║ contactId ║ projectId ║ lastName ║   type    ║
╠═══════════╬═══════════╬══════════╬═══════════╣
║         1 ║         1 ║ Foo      ║ architect ║
║         2 ║         1 ║ Owner 1  ║ owner     ║
║         3 ║         1 ║ Owner 2  ║ owner     ║
╚═══════════╩═══════════╩══════════╩═══════════╝

projectDetails
╔═══════════╦═════════════╗
║ projectId ║ projectName ║
╠═══════════╬═════════════╣
║         1 ║ Bar         ║
║         2 ║ Fizz        ║
╚═══════════╩═════════════╝

并且我正在通过搜索联系人的姓氏来选择projectName以及所有相关联系人。我使用它执行此操作的代码是

SELECT `det`.`projectName`, `owner`.`lastName` as `ownerLast`, `architect`.`lastName` as `archLast`,
FROM `projectDetails` as `det`
LEFT JOIN `contacts` as `owner`
    ON `owner`.`projectId` = `det`.`projectId` AND `owner`.`type`="owner"
LEFT JOIN `contacts` as `architect`
    ON `architect`.`projectId` = `det`.`projectId` AND `architect`.`type`="architect"
WHERE `architect`.`lastName` = "Foo"

这将生成两行

╔═════════════╦═══════════╦══════════╗
║ projectName ║ ownerLast ║ archLast ║
╠═════════════╬═══════════╬══════════╣
║ Bar         ║ Owner1    ║ Foo      ║
║ Bar         ║ Owner2    ║ Foo      ║
╚═════════════╩═══════════╩══════════╝

我想这有道理,但不是我想要的。 有没有一种方法可以将相同类型的结果进行汇总,例如汇总为

╔═════════════╦════════════════╦══════════╗
║ projectName ║   ownerLast    ║ archLast ║
╠═════════════╬════════════════╬══════════╣
║ Bar         ║ Owner1, Owner2 ║ Foo      ║
╚═════════════╩════════════════╩══════════╝

2 个答案:

答案 0 :(得分:1)

使用group_concat()

SELECT `det`.`projectName`, group_concat(`owner`.`lastName`) as `ownerLast`, `architect`.`lastName` as `archLast`,
FROM `projectDetails` as `det`
LEFT JOIN `contacts` as `owner`
    ON `owner`.`projectId` = `det`.`projectId` AND `owner`.`type`="owner"
LEFT JOIN `contacts` as `architect`
    ON `architect`.`projectId` = `det`.`projectId` AND `architect`.`type`="architect"
WHERE `architect`.`lastName` = "Foo"
group by `det`.`projectName`,`architect`.`lastName`

答案 1 :(得分:1)

使用group_concat()

SELECT `det`.`projectName`, group_concat( `owner`.`lastName`) as `ownerLast`, `architect`.`lastName` as `archLast`,
FROM `projectDetails` as `det`
LEFT JOIN `contacts` as `owner`
    ON `owner`.`projectId` = `det`.`projectId` AND `owner`.`type`="owner"
LEFT JOIN `contacts` as `architect`
    ON `architect`.`projectId` = `det`.`projectId` AND `architect`.`type`="architect"
WHERE `architect`.`lastName` = "Foo"
group by `det`.`projectName`,archLast