什么SQL查询多行,每行中有一个值相同?
我正在尝试插入以下类型的XML文件:什么SQL查询多行,每行中有一个值相同?,sql,Sql,我正在尝试插入以下类型的XML文件: <thing> <name>one</name> <type>metal</type> <type>round</type> </thing> <thing> <name>two</name> <type>round</type> </thing> &l
<thing>
<name>one</name>
<type>metal</type>
<type>round</type>
</thing>
<thing>
<name>two</name>
<type>round</type>
</thing>
<thing>
<name>three</name>
<type>metal</type>
<type>round</type>
</thing>
类型_模式
pattern_id type_id
1 1
1 2
2 1
类型
id txt
1 metal
2 round
关键是,我不想有一个关于事物和类型的表,而是一个关于事物
、类型
和类型
的表
我的问题是,给定一个类型列表,我应该如何编写SQL查询来获取模式id?
还是我走错了路?我会考虑
作为实体的事物和
作为实体键入(不知道它是实体还是值对象) 因此,相应地,您将有一个事物表和一个类型表
thing-table:
id | name
type table:
id | txt
然后一张多对多的桌子说
thingTypes:
thingId | typeId
当你想选择一件物品的所有类型时,只需查询thingId=“特定物品id”的thingTypes即可。或者,您可以查询thingTypes以获得特定的typeId,并获取引用特定类型的所有ThingID。在执行之前,您需要计算列表中的类型数:
select pattern_id
from type_pattern
where type_id in (...list of types...)
group by pattern_id
having count(*) = #of types in the list
或者,您可以根据匹配类型的数量对结果进行排序,以便获得完全匹配的模式以及接近匹配的模式:
select pattern_id, count(*) matches
from type_pattern
where type_id in (...list of types...)
group by pattern_id
order by 2 desc
更新:如果您不想要适合更多类型的模式,可以这样约束查询:
select pattern_id
from type_pattern t1
where type_id in (...list of types...) and not exists (
select 1
from type_pattern t2
where t2.pattern_id = t1.pattern_id
and t2.type_id not in (...list of types...))
group by pattern_id
having count(*) = #of types in the list
或者,如果您仍然想对模式进行排名,下面的查询将显示每个模式有多少“命中”和“未命中”,并按“命中”对它们进行排名:
有成百上千的
thing
元素,但它们都只有少数几种不同的类型
元素选择模式中的一种,这就是为什么我有一个单独的模式
表的原因。这并不能完全解决问题,因为它检测多个匹配的模式,即使该模式有更多不匹配的类型。
select pattern_id
from type_pattern t1
where type_id in (...list of types...) and not exists (
select 1
from type_pattern t2
where t2.pattern_id = t1.pattern_id
and t2.type_id not in (...list of types...))
group by pattern_id
having count(*) = #of types in the list
select pattern_id,
sum(case when type_id in (...list of types...) then 1 else 0 end) matches,
sum(case when type_id in (...list of types...) then 0 else 1 end) extras
from type_pattern
group by pattern_id
order by 2 desc