1

例如,我有一个带有一个列 id 的头表和一个带有 id、头 id(对头表 => 1 到 N 的引用)和一个值的位置表。现在我在 head-table 中选择一行,比如 id 1。我查看 position-table 并找到引用 head-table 并具有值 1337 和 1338 的 2 行。现在我想选择所有 head 也2 个位置,这些值分别为 1337 和 1338。位置 ID 不同,只有值不同,因为它不是 M 到 N 关系。谁能告诉我一个 SQL 语句?我不知道完成它:/

4

2 回答 2

0

假设你有:

Create table head
(
    id int
)

Create table pos
(
    id int,
    head_id int,
    value int
)

并且您需要按值查找重复项,然后我会使用:

  Select distinct p.head_id, p1.head_id
from pos p
join pos p1 on p.value = p1.value and p.head_id<>p1.head_id
where p.head_id = 1

对于特定的 head_id,或者对于每个 head_id 没有最后一个 where

于 2012-05-21T21:15:17.273 回答
0

假设位置表中给定 headid 的值不重复,并且它永远不会为 NULL,那么您可以使用以下逻辑执行此操作。在位置表上对您关心的特定头部位置进行完全外部连接。然后检查是否有完全匹配。

以下查询执行此操作:

select *
from (select p.headid,
             sum(case when p.value is not null then 1 else 0 end) as pmatches,
             sum(case when ref.value is not null then 1 else 0 end) as refmatches
      from (select p.value
            from position p
            where p.headid = <whatever>
           ) ref full outer join
           position p
           on p.value = ref.value and
              p.headid <> ref.headid
      ) t
where t.pmatches = t.refmatches

如果值中确实有 NULL,则可以使用合并来适应这些值。如果您有重复,您需要更清楚地指定在这种情况下要做什么。

于 2012-05-21T20:58:52.467 回答