0

我如何在这样的查询中使用 with?有没有办法在 TableList 中使用 tableIds?我可以将它们视为子查询吗?

select * from TestTable where tableId in 

(WITH TableList (tableId)
AS
(
SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
UNION ALL
SELECT t.tableId From OldTable as t
INNER JOIN TableList as p
ON t.ParenTableId = p.TableId
WHERE t.IsDeleted = 0
)
SELECT tableId FROM TableList
)

编辑:为了说明为什么我不能在 sql 的第一条语句中使用 with。


select TableId, IsDeleted,
( 
  select count(OtherId) OtherTable
  where otherTableId in 
  (WITH TableList (tableId)
  AS
  (
  SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
  UNION ALL
  SELECT t.tableId From OldTable as t
  INNER JOIN TableList as p
  ON t.ParenTableId = p.TableId
  WHERE t.IsDeleted = 0
  )
  SELECT tableId FROM TableList
  )
  ) as Ex1
from TestTable where tableId in (1,2,3)

我认为这说明了为什么我试图在 sql 查询中间使用 with 子句。

4

2 回答 2

1

我更喜欢在 中这样做JOIN,所以它看起来像这样。WITH语句始终是 sql 查询语句中的第一个。

如果有记录在公共表表达式上有多个匹配项,则DISTINCT在子句上应用关键字SELECT以使结果唯一。TestTable

WITH TableList (tableId)
AS
(
    SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
    UNION ALL
    SELECT t.tableId From OldTable as t
    INNER JOIN TableList as p
    ON t.ParenTableId = p.TableId
    WHERE t.IsDeleted = 0
)
SELECT  DISTINCT a.*
FROM    TestTable a
        INNER JOIN TableList b
            ON a.tableId = b.tableId

更新 1

WITH TableList (tableId)
AS
(
    SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
    UNION ALL
    SELECT t.tableId From OldTable as t
    INNER JOIN TableList as p
    ON t.ParenTableId = p.TableId
    WHERE t.IsDeleted = 0
)
SELECT  DISTINCT t.TableId, t.IsDeleted, f.totalCount
FROM    TestTable t
        INNER JOIN
        (
            SELECT  a.otherTableId, COUNT(DISTINCT a.OtherId) totalCount
            FROM    OtherTable a
                    INNER JOIN TableList b
                        ON b.tableId = a.otherTableId
            GROUP   BY otherTableId
        ) f ON t.tableId = f.otherTableId
WHERE   t.tableId in (1,2,3)
于 2013-03-29T14:10:13.570 回答
1

您需要在调用 SQL 之前定义您的 WITH CTE:

WITH TableList (tableId)
AS
(
    SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
    UNION ALL
    SELECT t.tableId From OldTable as t
        INNER JOIN TableList as p
            ON t.ParenTableId = p.TableId
    WHERE t.IsDeleted = 0
)
SELECT * 
FROM TestTable 
WHERE tableId in 
(
    SELECT tableId FROM TableList
)

编辑——根据您的评论,您可以在 VIEW 中定义递归 CTE,然后根据需要使用:

CREATE VIEW YourView AS 
WITH TableList (tableId)
AS
(
    SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
    UNION ALL
    SELECT t.tableId From OldTable as t
        INNER JOIN TableList as p
            ON t.ParenTableId = p.TableId
    WHERE t.IsDeleted = 0
)
SELECT * 
FROM TableList;
于 2013-03-29T14:10:49.333 回答