通常,WITH语句具有以下form
WITH subQ1 AS (SELECT SchoolID FROM Roster),
subQ2 AS (SELECT OpponentID FROM PlayerStats)
SELECT * FROM subQ1
UNION ALL
SELECT * FROM subQ2;
现在我想知道是否可以做这样的事情:
WITH
relevant_ids AS (SELECT ids FROM table WHERE condition),
actual_data AS (SELECT stuff FROM large_table WHERE id in relevant_ids)
我知道我可以使用第一个查询并将其直接放在第二个查询的where条件中,但是我觉得这不太容易阅读。
答案 0 :(得分:2)
要专门解决您的第二个查询...
WITH
relevant_ids AS (SELECT id FROM table WHERE condition),
actual_data AS (SELECT stuff FROM large_table WHERE id in (select id from relevant_ids))
SELECT * from actual_data
CTE中的代码仍必须是有效的SQL。
但是,请考虑仅使用联接。
WITH
relevant_ids AS (SELECT id FROM table WHERE condition)
SELECT
large_table.stuff
FROM large_table
INNER JOIN relevant_ids USING(id)