什么SQL查询多行,每个行的值相同?

时间:2010-10-29 06:54:08

标签: sql

我正在尝试插入以下类型的XML文件:

<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>

进入SQL数据库。有许多<thing>元素,每个元素都有一个或多个<type>个元素。有很多东西,但每个东西可能只有少量<type>元素的重复不同模式,所以我创建了一个thing表,其中包含id列和patternpattern的表格,type_pattern的表格,列type_idpattern_id,以及type的表格该字词的txt列,例如metalround,以及id列。在解析XML文件时,我希望将每个thing分类为特定的type_pattern,这是它匹配的类型模式。例如,上面的内容onethree符合metalround类型的模式,但two只有round的不同模式{1}}类型。所以上面的数据库表可能看起来像

 id   pattern_id name
 1    1          one
 2    2          two
 3    1          three

type_pattern

 pattern_id type_id
 1          1
 1          2
 2          1

 id  txt
 1   metal
 2   round     

重点是,我希望没有关于事物和类型的表,而是一个thingtype_patterntype的表。

我的问题是,给定一个类型列表,我应该如何编写SQL查询来获取模式ID?

或者我是以错误的方式解决这个问题?

2 个答案:

答案 0 :(得分:0)

我会考虑

作为一个实体的东西

键入作为实体(不知道它确实是实体还是值对象)

因此你会有一个东西表和一个类型表

thing-table:
id | name

type table:
id | txt

然后是一个多对多的表格

thingTypes:
thingId | typeId

当你想选择一个东西的所有类型时,只需查询thingTypes为thingId =“特定的东西id”。或者,您可以查询thingTypes以获取特定的typeId,并获取引用特定类型的所有thingIds。

答案 1 :(得分:0)

您需要在执行前计算列表中的类型数:

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

或者,如果你仍想对模式进行排名,这里的查询显示每个模式有多少“点击”和“未命中”,并按“点击”排名:

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