[英]Nested Query Alternatives in AWS Athena
我正在運行一個查詢,該查詢提供了一組非重疊的first_party_id - 與一個第三方相關聯但不與另一個相關聯的ID。 但是,此查詢不在Athena中運行,從而出現錯誤: Correlated queries not yet supported.
正在查看prestodb文檔, https ://prestodb.io/docs/current/sql/select.html(Athena是引擎蓋下的prestodb),用於替代嵌套查詢。 給出的with statement
示例似乎沒有很好地轉換為this not in
子句。 想知道嵌套查詢的替代方法是什么 - 查詢如下。
SELECT
COUNT(DISTINCT i.third_party_id) AS uniques
FROM
db.ids i
WHERE
i.third_party_type = 'cookie_1'
AND i.first_party_id NOT IN (
SELECT
i.first_party_id
WHERE
i.third_party_id = 'cookie_2'
)
可能有更好的方法來做到這一點 - 我很想看到它! 我能想到的一種方法是使用外連接。 (我不確定你的數據是如何構建的,所以請原諒這個人為的例子,但我希望它可以翻譯好。)這個怎么樣?
with
a as (select *
from (values
(1,'cookie_n',10,'cookie_2'),
(2,'cookie_n',11,'cookie_1'),
(3,'cookie_m',12,'cookie_1'),
(4,'cookie_m',12,'cookie_1'),
(5,'cookie_q',13,'cookie_1'),
(6,'cookie_n',13,'cookie_1'),
(7,'cookie_m',14,'cookie_3')
) as db_ids(first_party_id, first_party_type, third_party_id, third_party_type)
),
b as (select first_party_type
from a where third_party_type = 'cookie_2'),
c as (select a.third_party_id, b.first_party_type as exclude_first_party_type
from a left join b on a.first_party_type = b.first_party_type
where a.third_party_type = 'cookie_1')
select count(distinct third_party_id) from c
where exclude_first_party_type is null;
希望這可以幫助!
您可以使用外部聯接:
SELECT
COUNT(DISTINCT i.third_party_id) AS uniques
FROM
db.ids a
LEFT JOIN
db.ids b
ON a.first_party_id = b.first_party_id
AND b.third_party_id = 'cookie_2'
WHERE
a.third_party_type = 'cookie_1'
AND b.third_party_id is null -- this line means we select only rows where there is no match
對於可能返回NULL
值的子查詢使用NOT IN
時也應該小心,因為條件始終為true。 您的查詢是將a.first_party_id
與NULL
進行比較,這將始終為false,因此NOT IN
將導致條件始終為true。 討厭的小騙子。
避免這種情況的一種方法是避免使用NOT IN
或向子查詢添加條件,即AND third_party_id IS NOT NULL
。
請參閱此處以獲得更長的解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.