Sql Server连接表并合并一些行

时间:2016-05-24 17:36:17

标签: sql sql-server

有三个表格如下:A代表塔牌信息,B代表后卫信息,C代表他们的关系

TableA:
TowerID  TowerName  DefenderName
1        TwA        DefA
2        TwB        DefB
3        TwC        DefA,DefB

TableB:
DefenderID  DefenderName
1           DefA
2           DefB

TableC:
TowerID  DefenderID
1        1
2        2
3        1
3        2

我使用以下sql语句加入它们:

SELECT * FROM
(SELECT TableA.TowerID,TableA.TowerName,TableA.DefenderName,TableC.DefenderID
FROM TableA,TableC
WHERE TableA.TowerID = TableC.TowerID) AS tbl

TowerID  TowerName  DefenderName  DefenderID
1        TwA        DefA          1
2        TwB        DefB          2
3        TwC        DefA,DefB     1
3        TwC        DefA,DefB     2

如果DefA登录,我可以附加该语句:

WHERE DefenderID = 1

他会看到

TowerID  TowerName  DefenderName  DefenderID
1        TwA        DefA          1
3        TwC        DefA,DefB     1

如果是DefB登录,则DefenderID = 2。

如果国王登录,我想告诉他类似的事情:

TowerID  TowerName  DefenderName
1        TwA        DefA
2        TwB        DefB
3        TwC        DefA,DefB

如何修改sql语句以显示上面的表格,当DefA或DefB登录时,我需要做的是将sql附加“WHERE DefenderID ='x'”,他们只能看到他们的自己的信息?

(不需要列DefenderID)

2 个答案:

答案 0 :(得分:0)

SELECT * 
FROM   (SELECT DISTINCT   --- include this
               tablea.towerid, 
               tablea.towername, 
               tablea.defendername, 
               tablec.defenderid 
        FROM   tablea, 
               tablec 
        WHERE  tablea.towerid = tablec.towerid) AS tbl 

答案 1 :(得分:0)

如果要使用where子句,则听起来就像使用动态查询一样。如果你有一个与会话登录匹配的用户表,它可以变得更复杂,但现在这应该有效:

Declare @Sql Varchar(8000)
Set @Sql = 
'SELECT * FROM
(SELECT TableA.TowerID,TableA.TowerName,TableA.DefenderName
FROM TableA,TableC
GROUP BY TowerID, TowerName, DefenderName
WHERE TableA.TowerID = TableC.TowerID) AS tbl'

If @User = 'DefA'
  Set @Sql = @Sql + ' Where DefenderID = 1'
Else If @User = 'DefB'
  Set @Sql = @Sql + ' Where DefenderID = 2 '
Else If @User = 'King'
  Set @Sql = @Sql + ' Where 1 = 1 '
Else 
  Set @Sql = 'Error handling goes here, for now query will error instead '

Exec (@Sql) 

在这里,我设置@Sql = @Sql + 'Where 1=1',只需一个空字符串@Sql = @Sql + ' '