两个表之间的SQL Server条件连接

时间:2015-10-22 11:07:26

标签: sql sql-server tsql

假设我有表NSString *host = @"TEST.local"; CFHostRef hostref = CFHostCreateWithName(kCFAllocatorDefault,(__bridge CFStringRef)host); CFStreamError *err; Boolean lookup = CFHostStartInfoResolution(hostref, kCFHostAddresses, err); NSArray* addresses = (__bridge NSArray*)CFHostGetAddressing(hostref, &lookup); if(addresses.firstObject!=nil) { struct sockaddr_in *firstaddress = (struct sockaddr_in*)CFDataGetBytePtr((__bridge CFDataRef)addresses.firstObject); NSString *strDNS = [NSString stringWithUTF8String:inet_ntoa(firstaddress->sin_addr)]; } A,我想用这样的条件连接创建一个选择查询

B

4 个答案:

答案 0 :(得分:2)

使用CASE可以实现这一点。请看这个:

SELECT *
FROM A AS a
INNER JOIN B AS b
    ON CASE
        WHEN @customParam = 1 AND b.Id = a.B_Id THEN 1
        WHEN @customParam = 0 AND b.someid = a.someid THEN 1
        ELSE 0
    END = 1;

您的查询将检查您的@customParam值,并根据该值来比较您的JOIN条件以及是否匹配 - 它将导致1,然后将其与1(END = 1;)进行比较并返回给您结果

答案 1 :(得分:1)

您可以使用IF ELSE

IF @customParam = 1
BEGIN
  SELECT * FROM A a JOIN B b ON a.B_Id = b.Id 
END
ELSE
BEGIN
  SELECT * FROM A a JOIN  B b ON b.someid=a.someid
END

在一个声明中(表现不佳):

SELECT * 
FROM A a 
JOIN B b 
  ON (@customParam = 1 AND a.B_Id = b.Id)
  OR (@customParam = 0 AND b.someid=a.someid)

您还可以使用Dynamic-SQL并构建自定义查询:

DECLARE @sql NVARCHAR(MAX) = 
  N'SELECT * 
    FROM A a 
    JOIN B b
      ON <placeholder>';

SET @sql = REPLACE(@sql, '<placeholder>',
                   CASE WHEN @customParam = 1 THEN 'a.B_Id = b.Id'                 
                        ELSE 'b.someid=a.someid'
                   END);    


EXEC [dbo].[sp_executesql]
     @sql;

LiveDemo

答案 2 :(得分:1)

您可以使用left join在一个查询中执行此操作。但是,您无法真正使用*来获取列。您需要对原始查询使用coalesce()(或类似功能):

select a.*, coalesce(b1.col1, b2.col1) as col1, . . ..
from A a left join
     B b1
     on b1.B_Id = a.Id and customParam is true left join
     B b2
     on b2.someid = a.someid and customerParam is not true

这可以利用&#34; id&#34;和&#34; someid&#34;。

答案 3 :(得分:1)

是ID int?
不是最好的方式,而是另一种方式

declare @customParam bit;
set @customParam = 1;
select * from A  
join B  
on @customParam * A.B_Id + abs(@customParam-1) * A.someid 
 = @customParam * B.Id   + abs(@customParam-1) * B.someid;