0

我有 2 个实体,比如实体 [x] 和 [y]。这两个实体都与一些标签相关联。实体 [y] 用于搜索相似的 [x] 实体。例如。如果实体 [y] 由标签“书”和“博客”组成,我想要一个包含这两个标签的所有 [x] 实体的列表。

我的表架构是:

[x] 
entity_id int    // its a foreign key from entity table  
tag varchar      // this is the tag to be matched
(one entity can have multiple tags hence multiple rows of same entity
id will be inserted)


[y]
entity_id int    // again a foreign key from entity2 table
tag varchar      // tags again
(same comment comes here too)

再举一个例子,假设我有一个 [y] entity_id 10,而这 10 个 entity_id 与 3 个标签相关联,比如“bus”、“train”和“plane”,当我想使用这个 entity_id 10 进行查找时,我想要与所有这 3 个标签关联的 [x] entity_ids 列表。[x] entity_id 也可以有额外的标签。

4

1 回答 1

1

给定 ay.entity_id作为参数,10在此示例中,此查询返回x没有实例的每条记录,其中存在y没有对应记录的x记录:

SELECT
    *
FROM
    x
WHERE NOT EXISTS (
    SELECT *
    FROM 
        y LEFT JOIN
        x subX 
            ON subX.tag = y.tag
            AND subX.entity_id = x.entity_id
    WHERE 
        y.entity_id = 10
        AND subX.entity_id IS NULL  
)
于 2012-11-16T22:00:54.203 回答