我有一个名为Attributes
的表,其中包含用ItemId
标识的项目的属性名称和值的包。
╔════════╦═══════╦══════════╗
║ ItemId ║ Name ║ Value ║
╠════════╬═══════╬══════════╣
║ 1 ║ color ║ green ║
║ 1 ║ mood ║ happy ║
║ 1 ║ age ║ 5 ║
║ 1 ║ type ║ A ║
║ 2 ║ color ║ blue ║
║ 2 ║ mood ║ sad ║
║ 2 ║ age ║ 5 ║
║ 2 ║ type ║ B ║
║ 3 ║ color ║ red ║
║ 3 ║ mood ║ angry ║
║ 3 ║ age ║ 5 ║
║ 3 ║ type ║ B ║
║ 4 ║ color ║ yellow ║
║ 4 ║ mood ║ whatever ║
║ 4 ║ age ║ 7 ║
║ 5 ║ color ║ green ║
║ 5 ║ mood ║ happy ║
║ 5 ║ age ║ 2 ║
║ 5 ║ type ║ D ║
╚════════╩═══════╩══════════╝
这是一个具有上述结构和数据的SQLFiddle:http://sqlfiddle.com/#!17/08c4b/1
我想获得一组不同的属性名称列表。
ItemId
+ Name
组合是唯一的(同一项目的相同属性不能有多个值)。
在上面的示例中,这样的组将是color + mood
,因为以下内容始终为真:
green
时,情绪为happy
red
时,情绪为angry
blue
时,情绪为sad
yellow
时,情绪为whatever
例如,如果有一个额外的项目具有颜色red
和情绪happy
,则会使上述相关性无效。
此外,在此数据集中:
年龄与类型无关,因为:
5
,类型为A
5
,但类型为B
颜色与类型无关,因为:
green
,类型为A
green
,但类型为D
依旧......
是否可以编写自动发现属性之间这些相关性的SQL语句?
答案 0 :(得分:1)
绝对有可能。一种可能不是最简单的方法就是这样。
with pairs as (
select l.*, r.name as name2, r.value as value2
from Attribute l join Attribute r on l.ItemId = r.ItemId and l.name < r.name),
counts as (
select name,name2,count(distinct value2)
from pairs l join pairs r using (name,value,name2,value2)
where l.itemid <= r.itemid group by name,value,name2)
select name,name2 from counts group by name, name2 having max(count)=1;
此版本假设缺少的属性与所有内容相关联,这可能是也可能不是预期的内容。
答案 1 :(得分:0)
with associations as (
-- associations of
select
a1."ItemId" as Id1,
a2."ItemId" as Id2,
a1."Name" as Name,
a1."Value" as Value1,
a2."Value" as Value2
from Attribute a1
join Attribute a2
on a1."ItemId" < a2."ItemId"
and a1."Name" = a2."Name"
),
names as (
select distinct "Name"
from Attribute
)
select *
from names n1
join names n2
on n1."Name" < n2."Name"
and not exists (
-- try to find a miscorrelation
select *
from associations s1
join associations s2
on s1.Id1 = s2.Id1
and s1.Id2 = s2.Id2
and s1.name in (n1."Name", n2."Name")
and s2.name in (n1."Name", n2."Name")
and s1.value1 = s1.value2
and s2.value1 != s2.value2
)
;
SQLFiddle链接:http://sqlfiddle.com/#!17/08c4b/32