只是为了澄清我无法更改表结构,因此请省略“您应该将表更改为这个和那个”答案,谢谢。
所以我有一个表entities_attributes_values,其中实体有很多属性和该属性的值,基本上想象3个字段:
- 实体 ID
- entity_attributes_id
- 值(value)
因为每个实体属性及其值都在行上获取更多值并不那么容易,所以我正在考虑多个自联接,并且因为这个查询非常常见,所以我创建了一个 View ,它是用这个查询构建的:
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
所以这可行,但我有一个问题,我得到“重复”值,并且它并不是真正重复,但重点是,在我看来,我希望每个实体只是一行及其所有属性值 但我得到的是这个:
因此,正如您所看到的,前三个结果对我不利,我只需要第四个结果,其中我拥有有关一个实体的所有数据。
预先感谢您的帮助!
最佳答案
尝试使用条件聚合:
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;
这将使向 View 添加新属性变得容易。另外,不要使用单引号来分隔列名称。单引号只能用于日期和时间常量。
关于Mysql:创建具有多个自联接的 View ,结果不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31023946/