我想存储子查询中的值列表,以便在IN语句中重复使用我的查询:
WITH ListOfIds AS (SELECT Id FROM Users)
(SELECT COUNT(*) FROM Foo WHERE Foo.UserId IN ListOfIds)
UNION
(SELECT COUNT(*) FROM Bar WHERE Bar.UserId IN ListOfIds)
无效。我怎么能这样做?
答案 0 :(得分:2)
您可以使用:
WITH ListOfIds AS (SELECT Id FROM Users)
SELECT COUNT(*)
FROM Foo
WHERE Foo.UserId IN (SELECT Id FROM ListOfIds)
UNION
SELECT COUNT(*)
FROM Bar
WHERE Bar.UserId IN (SELECT Id FROM ListOfIds)
虽然这有点无意义。
可能UNION ALL
代替UNION
。我没有看到跳过计数的重点。
你应该坚持:
SELECT COUNT(*)
FROM Foo
WHERE Foo.UserId IN (SELECT Id FROM Users)
UNION
SELECT COUNT(*)
FROM Bar
WHERE Bar.UserId IN (SELECT Id FROM Users)
我认为查询优化器非常智能,可以获得Id
列表一次。