从包含WHERE的表中选择并从包含结果的表中选择

时间:2015-09-22 15:07:38

标签: sql sql-server

我有一个名为clients的表。表中有父子关系。这是它的样子:

clientID     |     code    |    cName    |   sub
------------      ------        -----       -----
1                  STK        Stackover       0    <---- parent
2                  GOGL        Google         0    <---- parent
3                  MSFT       Microsoft       1    <-- child of stackover

我试图做的是一个类似的搜索,但是我希望我喜欢搜索,以便拉起父母和孩子,反之亦然。所以在这个例子中,如果我搜索&#34; stk&#34; OR&#34; Stackover&#34;,我不仅得到Stackover,还有Microsoft。如果我搜索微软,我会得到微软和堆栈。我怎么把它关掉?这是我现有的查询:

SELECT  code, cName 
FROM    clients 
WHERE   cName LIKE '%Stack%' 
OR      code LIKE '%Stack%' 
AND     active='True' 
ORDER BY cName

这只会返回堆栈。

2 个答案:

答案 0 :(得分:1)

DECLARE @myTable TABLE
  (
    clientID INT ,
    code VARCHAR(10) ,
    cName VARCHAR(10) ,
    sub INT
  );

INSERT  @myTable ( [clientID], [code], [cName], [sub] )
VALUES  ( 1, 'STK', 'StackOver', 0 ),
        ( 2, 'GOGL', 'Google', 0 ),
        ( 3, 'MSFT', 'Microsoft', 1 );


WITH  t ( clientId, code, cname, rootId )
        AS (
             SELECT clientID, code, cName, clientID AS rootId
             FROM   @myTable AS [mt]
             WHERE  [sub] = 0
             UNION ALL
             SELECT mt.clientID, mt.code, mt.cName, t.[rootId]
             FROM   @myTable AS [mt]
             INNER JOIN t ON t.clientId = mt.[sub]
           ),
      roots
        AS (
             SELECT rootId
             FROM   t
             WHERE  cname LIKE '%Stack%' OR
                    code LIKE '%Stack%'
           )
  SELECT  [t].[code], [t].[cname]
  FROM    t
  INNER JOIN roots rt ON [rt].[rootId] = [t].[rootId];

答案 1 :(得分:0)

这是简单的解决方案

SELECT * FROM (
    SELECT c1.clientid,c1.code, c1.cName,c1.sub FROM clients c1
    WHERE c1.cName LIKE '%Stack%' OR c1.code LIKE '%Stack%'
    UNION ALL
    SELECT c2.clientid,c2.code, c2.cName,c2.sub FROM clients c1 
        LEFT JOIN clients c2 ON c2.sub = c1.clientid
    WHERE c1.cName LIKE '%Stack%' OR c1.code LIKE '%Stack%'
    UNION ALL 
    SELECT c2.clientid,c2.code, c2.cName,c2.sub FROM clients c1
        LEFT JOIN clients c2
    ON c1.sub = c2.clientid
    WHERE c1.cName LIKE '%Stack%' OR c1.code LIKE '%Stack%'
) a
WHERE a.clientid IS NOT null