在两个多对多关系之间进行选择

时间:2014-12-15 10:12:55

标签: sql sql-server many-to-many self-join

我有四个表Level,Tag,Level_Tag和Tag_hierarchy。如何选择具有此条件的级别的所有标记id_tag = id_parent ,这意味着标记是根。我可以从连接表中选择(也许不是一个好的表现?)但我不知道如何在这里添加其他自联接。

SELECT        level.name, tag.id, tag.name
FROM            level INNER JOIN
                         tag_level ON level.id = tag_level.id_level INNER JOIN
                         tag ON tag_level.id_tag = tag.id
WHERE        (level.Id =  @id)

标签表包含数千行,我真的很担心内存和性能问题。 你能帮帮我吗?这是架构

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个:

;with cte as
(select id_tag
 from tag_hierarchy where id_tag = id_parent)

select l.name, t.id, t.name
from cte c
inner join tag t on t.id = c.id_tag
inner join tag_level tl on t.id = tl.id_tag
inner join level l on tl.id_level = l.id
where l.lid = @id

答案 1 :(得分:1)

也许你可以添加另一个存在。像这样:

SELECT        
    level.name, 
    tag.id, 
    tag.name
FROM            
    level 
    INNER JOIN tag_level 
        ON level.id = tag_level.id_level 
    INNER JOIN tag 
        ON tag_level.id_tag = tag.id
WHERE        
    (level.Id =  @id)
    AND EXISTS
    (
        SELECT NULL 
        FROM Tag_hierarchy
        WHERE  Tag_hierarchy.id_tag=tag.id
        AND Tag_hierarchy.id_tag=Tag_hierarchy.id_parent
    )