SQL Server查询从View中检索所有内容

时间:2016-09-27 08:11:23

标签: sql-server

我有一个SQL视图,类似于下面的视图:

    map_id  | type_id | path
    1         1         0
    2         2         0
    3         3         0
    4         1         A>B
    5         1         A>B>C
    6         2         T>Z
    7         2         T>Z>X
    8         3         U
    9         3         X>Y  
   10         1         D

另一张桌子,tblRoles

role_group_id  | type_id  | map_id
1                1          1
2                1          4

我想构建一个查询,其中包含map_id所有role_group_id map_id = 1的所有map_id,其余部分只应包含相应的role_group_id | type_id | map_id | path 1 1 4 A>B 1 1 5 A>B>C 1 1 10 D 1 1 1 0 2 1 4 A>B

因此,查询结果应如下所示:

<form action="product_detail1.php" method="GET">
  <input name="search" style="padding: 3px 0px 3px 30px;" type="text" id="skills" class="search1" placeholder="Cerca per codice">
  <label style="position: absolute; z-index: 2; top: 4px; left: 3px; font-size: 18px;" for="skills" class="glyphicon glyphicon-search" rel="tooltip" title="search"></label>
</form>

有人能指出我正确的方法吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

尚未对此进行测试,我希望这应该可行。

SELECT r.role_group_id
       ,r.type_id
       ,sv.map_id
       ,sv.path
FROM tblRoles r
LEFT JOIN sampleView sv ON r.type_id = sv.type_id
WHERE r.map_id = 1
UNION
SELECT r.role_group_id
       ,r.type_id
       ,r.map_id
       ,sv.path
FROM tblRoles r
INNER JOIN sampleView sv ON r.map_id = sv.map_id
WHERE r.map_id <> 1 

答案 1 :(得分:0)

您可以使用UNION

  

@rosuandreimihai:当map_id = 1时选择全部,如果map_id不同,则只选择   相应的行

DECLARE @CurrentMapId INT = 1

SELECT * FROM FirstTable
WHERE
    TYPE_ID IN 
    (
        SELECT r.type_id FROM tblRoles r
        WHERE           
            map_id = @CurrentMapId
    )
UNION
SELECT * FROM FirstTable
WHERE
    map_id   IN 
    (
        SELECT r.map_id FROM tblRoles r
        WHERE           
            @CurrentMapId = 1 OR
            map_id = @CurrentMapId
    )