我有两张桌子:
客户
AccountId Cdescr other customer cols...
1000 ABC
科
AccountId BranchId Bdescr other branch cols...
1000 1 AAA
1000 2 BBB
我无法找到实现此目的的方法
AccountId BranchId Cdescr Bdescr branchCols... customerCols...
1000 0 ABC NULL NULL VALUES...
1000 1 NULL AAA VALUES... NULL
1000 2 NULL ABC VALUES... NULL
在缺省的customer表上,缺省的branchId列应默认设置为0。
我需要能够搜索Cdescr和Bdescr,并且Customer表上的每个匹配都应该选择相关的分支。如果仅在分支表上使用,则应该选择相关的客户行
使用FULL OUTER JOIN加入branchId实际上无法正常工作
SELECT *
FROM (
SELECT *, 0 as branchId
FROM Customers
WHERE CONCAT(an_descr1, an_descr2) LIKE '%SEARCH_STRING%'
) a
FULL OUTER JOIN Branch d ON d.branchId = a.branchId
在当前查询中我无法在分支表中搜索</ p>
答案 0 :(得分:1)
试试这个:
DECLARE @tCust TABLE(
AccountId INT
,Cdescr NVARCHAR(10)
);
DECLARE @tBranch TABLE(
AccountId INT
,BranchId INT
,Bdescr NVARCHAR(10)
);
INSERT INTO @tCust VALUES(1000, 'ABC');
INSERT INTO @tBranch VALUES(1000, 1, 'AAA'), (1000, 2, 'BBB');
WITH cte AS(
SELECT ISNULL(b.AccountId, c.AccountId) AccountId, ISNULL(b.BranchId, 0) BranchId, bDescr, cDescr
FROM @tCust c
FULL OUTER JOIN @tBranch b ON b.AccountId = c.AccountId
UNION ALL
SELECT c.AccountId, 0 BranchId, NULL bDescr, cDescr
FROM @tCust c
)
SELECT *
FROM cte
WHERE CONCAT(Bdescr, Cdescr) LIKE '%ABC%'
答案 1 :(得分:0)
您需要使用UNION
。
null
的客户字段
Branch
字段null
的分支字段
Customers
字段的值。您需要选择明确所有字段。 UNION的所有查询需求都提供相同顺序和相同类型的字段。
select
AccountId,
0 as BranchId,
Customers.Cdescr,
null as Bdescr ,
Customers.C1,
Customers.C2,
null as B1,
null as B2
from
Customers
union all
select
Branch.AccountId,
Branch.BranchId,
null Cdescr,
Branch.Bdescr ,
null as C1,
null as C2,
Branch.B1,
Branch.B2
from
Branch
答案 2 :(得分:0)
尝试使用coalesce
将null
转换为空字符串:
SELECT
*
FROM
Customers C
FULL OUTER JOIN Branch B ON
C.AccountId = B.AccountId
where
CONCAT(
coalesce(C.an_descr1,''),
coalesce(C.an_descr2,''),
coalesce(B.another_descr,'')
) LIKE '%SEARCH_STRING%'