Mysql:创建具有多个自联接的 View ,结果不重复

标签 mysql duplicates self-join sql-view

只是为了澄清我无法更改表结构,因此请省略“您应该将表更改为这个和那个”答案,谢谢。

所以我有一个表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

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

enter image description here

因此,正如您所看到的,前三个结果对我不利,我只需要第四个结果,其中我拥有有关一个实体的所有数据。

预先感谢您的帮助!

最佳答案

尝试使用条件聚合:

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/

相关文章:

php - PHP 5.6.30 中不存在 mysqli_connect 和 mysql_connect

python - 删除重复项,但根据不同列中的排序保留一个

mysql - 如何使用 phpMyAdmin 添加指向同一个表的外键?

mysql - CSV 到 MySQL : Single table vs. 多个表?

mysql - 添加到远程数据库

php - 哪个更好,使用 SQL 查询进行数据操作或在 php 中操作数组中的数据?

ios - Swift:如何从 TableView 中删除重复项?

mysql - 自连接中的内连接 - MySql

mysql - 自连接一个表来创建 "AND-filter"的最简单方法?

mysql - 如何使用hibernate检查表中是否存在数据