【问题标题】:SQL Query to compare attributes stored in the same database table side by sideSQL Query 并排比较存储在同一个数据库表中的属性
【发布时间】:2012-08-13 16:00:29
【问题描述】:

假设我们有一个这样的表:

entity_id attribute_name attribute_value
----------------------------------------
0         server         alpha
1         server         beta
0         priority       1
1         priority       2
1         comment        some comment
2         server         gamma

对于 PostgreSQL 来说,会给出这些结果的查询是什么:

server    alpha     beta
priority  1         2

注意:

  • 我们假设我们只想比较 id 为 0 和 1 的实体。
  • 如果两个实体都没有一个属性,则可以忽略它

【问题讨论】:

  • serveralphabeta在查询结果标题标题中,还是第一行数据?
  • 我会假设它们是第一行,因为它们的 id 也是 0 和 1。
  • 答案在 SQL Server、Postres、MySQL 中是不同的……您已经有足够长的时间知道这一点了。请适当地标记您的问题。除此之外,您似乎正在使用 SQL 来进行显示格式化。那不是数据库的工作。您可以使用普通的旧 SELECT columns... FROM table 查询选择这些行,然后在您的应用程序代码中并排显示您想要的内容。

标签: sql postgresql join


【解决方案1】:

试试这个

CREATE TABLE test1(entity_id int,attribute_name varchar(100), attribute_value varchar(100))
insert into test1
VALUES(0,'server','alpha'),
(1,'server','beta'),
(0,'priority','1'),
(1,'priority','2'),
(2,'server','gamma')

;WITH CTE as(
select attribute_name,(select STUFF((select ','+ attribute_value from test1 where entity_id in (0,1) and attribute_name=t1.attribute_name  for XML path('')),1,1,'') ) as colms
from test1 t1
where entity_id in (0,1)
group by attribute_name)

select attribute_name,LEFT(colms,CHARINDEX(',',colms,1)-1) as attr_value1,RIGHT(colms,len(colms)-CHARINDEX(',',colms,1)) as attr_value2 from CTE
order by 1 desc

【讨论】:

    【解决方案2】:

    这应该在 TSQL 中工作:

    SELECT T.attribute_name, A.attribute_value, B.attribute_value
    FROM theTable T
    CROSS APPLY (
        SELECT T0.attribute_value
        FROM theTable T0
        WHERE T0.entityId = 0 AND T0.attribute_name = T.attribute_name
    ) A
    CROSS APPLY (
        SELECT T1.attribute_value
        FROM theTable T1
        WHERE T1.entityId = 1 AND T1.attribute_name = T.attribute_name
    ) B
    

    您可以添加更多 CROSS APPLYs 以包含更多实体的结果。如果不能保证每个 entityId/name 对都有 attribute_value,则可以将其替换为 OUTER APPLY(或等效使用 INNER/LEFT JOINs)

    【讨论】:

      【解决方案3】:

      至少在 MySQL 中有效:

      select attr_list.attribute_name, t0.attribute_value, t1.attribute_value
        from (select distinct attribute_name from tbl) as attr_list
        left join tbl as t0 on t0.attribute_name = attr_list.attribute_name 
         and t0.entity_id = 0
        left join tbl as t1 on t1.attribute_name = attr_list.attribute_name 
         and t1.entity_id = 1
      

      【讨论】:

        猜你喜欢
        • 2013-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 2013-12-04
        • 1970-01-01
        相关资源
        最近更新 更多