SQL Server - 内部联接 - 条件语句

时间:2014-06-12 05:54:30

标签: sql sql-server sql-server-2008 inner-join

我正在使用SQL Server 2008并具有以下方案:

我的Table a字段为idgroupId

我有Table b字段idgroupId

Table b中的规则是:

If a.id = 0, then a.groupId = b.groupId
Else a.id = b.id (in which case a.groupId = 0)

这两个表格也由agrId关联,以便a.agrId = b.agrId

如何在满足上述规则的同时加入这些表格?

更新:对于不明确的道歉,我已更新规则并在下面添加了我的尝试:

select * from a
inner join b
on a.agrId = b.agrId
where (
    (b.id > '0' and b.groupId = '0') 
    or
    (b.groupId > '0' and b.id = '0')
  )

3 个答案:

答案 0 :(得分:2)

试试这个

SELECT *
FROM TableA A
INNER JOIN TableB B
    ON (B.ID = 0 AND A.groupId = B.groupId)
        OR (B.groupId = 0 AND A.id = B.id)

答案 1 :(得分:0)

它需要的是一个计算结果为true或false的表达式,以指示是否应该连接这两行。所以根据你所说的,这将是连接条件:

select  *
from    tA a 
        inner join tB b 
            on (a.id = 0 and a.groupid = b.groupid) 
            or (a.groupid = 0 and a.id = b.id)

答案 2 :(得分:0)

试试这个:

SELECT *
FROM   a INNER JOIN
       b ON a.agrId = b.agrId
WHERE  (b.id = '0' AND b.groupId = a.groupId) 
       or
       (b.groupId = '0' AND b.id = b.id)