Mysql:创建一个包含多个自连接的视图,结果中没有重复项

时间:2015-06-24 10:18:14

标签: mysql duplicates self-join sql-view

只是为了澄清我无法更改表格结构,所以请忽略“你应该把表改成这个和那个”答案,谢谢。

所以我有一个表 entities_attributes_values ,其中一个实体有很多属性和该属性的值,基本上想象3个字段:

  • entity_id
  • entity_attributes_id

因为每个实体属性及其值在行上获取更多值并不是那么容易我想到多个自连接,并且因为这个查询将非常常见,我创建了一个视图,它是使用此查询构建的:

SELECT `L1`.`entity_id`,
       `L1`.`value` as 'company_id',
       `L2`.`value` as 'entity_name',
       `P`.`value` as 'person_name',
       `L4`.`value` as 'establishment_id',
       `L5`.`value` as 'department_id'
FROM `entities_attributes_values` `L1`
LEFT JOIN `entities_attributes_values` `L2` ON `L1`.`entity_id` = `L2`.`entity_id` AND `L2`.`entity_attributes_id` = 1
LEFT JOIN `entities_attributes_values` `L3` ON `L1`.`entity_id` = `L3`.`entity_id` AND `L3`.`entity_attributes_id` = 3
LEFT JOIN `persons_attributes_values` `P` ON `L3`.`value` = `P`.`core_persons_id` AND `P`.`core_persons_attributes_id` = 4
LEFT JOIN `entities_attributes_values` `L4` ON `L1`.`entity_id` = `L4`.`entity_id` AND `L4`.`entity_attributes_id` = 12
LEFT JOIN `entities_attributes_values` `L5` ON `L1`.`entity_id` = `L5`.`entity_id` AND `L5`.`entity_attributes_id` = 13
WHERE `L1`.`entity_attributes_id` = 2

所以这有效,但我有一个问题,我得到“重复”的值,它不是真的重复,但重点是,在我看来,我希望每个实体只有一行,其所有属性值但我得到了这个:

enter image description here

因为你可以看到前三个结果对我不利,我只需要第四个结果,其中我拥有关于一个实体的所有数据。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

请尝试使用条件聚合:

select eav.entity_id,
       max(case when entity_attributes_id = 2 then eav.value end) as company_id,
       max(case when entity_attributes_id = 1 then eav.value end) as entity_name,
       max(case when entity_attributes_id = 3 then eav.value end) as company_name,
       . . .
from entities_attributes_values eav
group by eav.entity_id;

这样可以轻松地向视图添加新属性。另外,不要使用单引号来分隔列名。单引号只能用于日期和时间常量。