如何将数据从WITH语句转换为集合?

时间:2017-05-17 09:48:06

标签: postgresql

我有以下查询:

WITH doorbot_data AS
(SELECT id FROM doorbots WHERE)

SELECT dings.id, doorbots.id
FROM dings
INNER JOIN doorbots ON dings.doorbot_id = doorbots.id
WHERE doorbots.id = ...   <---
      and deleted_at is null
ORDER BY dings.created_at;

首先,我选择doorbot_data,它就像id's的集合。

然后我想在WHERE中使用它:WHERE doorbots.id = doorbot_data.id。但是当我运行它时,我得到了missing FROM-clause entry for table "doorbot_data"

如果我使用id之类的123

,那么一切正常
SELECT dings.id, doorbots.id
FROM dings
INNER JOIN doorbots ON dings.doorbot_id = doorbots.id
WHERE doorbots.id = 123   <---
      and deleted_at is null
ORDER BY dings.created_at;

所以我认为我需要将doorbot_data转换为数组并使用它 WHERE doorbots.id IN (_array_)。这是正确的想法吗?怎么做?

1 个答案:

答案 0 :(得分:0)

你在寻找简单的加入吗?:

WITH doorbot_data AS
(SELECT id FROM WHERE)
SELECT dings.id, doorbots.id
FROM dings
INNER JOIN doorbots ON dings.doorbot_id = doorbots.id
JOIN doorbot_data ON doorbots.id = doorbot_data .id
ORDER BY dings.created_at;