【问题标题】:Use an array coming from a "with" statement使用来自“with”语句的数组
【发布时间】:2021-08-03 12:48:26
【问题描述】:

我有 ids 我可以通过这个请求收集:

SELECT array_agg(DISTINCT mc.id) as liste_ids
FROM mots_cles mc
WHERE mc.mot ILIKE '%Test%'

我想请求另一个表,其中的列与此数组有交集:

SELECT
  a.titre,
  a.id
FROM articles a
WHERE a.motscles && [THE ARRAY]

我尝试用这种结构写一个请求:

WITH xxx AS (
    SELECT array_agg(DISTINCT mc.id) as liste_ids
    FROM mots_cles mc
    WHERE mc.mot ILIKE '%Test%'
)
    SELECT
      a.titre,
      a.id
    FROM articles a
    WHERE a.motscles && xxx.liste_ids::integer[]

但正如您可能已经猜到的那样,它不起作用。我怎么写我的请求,我感觉我离结果不远了。

提前致谢。

【问题讨论】:

    标签: sql arrays postgresql


    【解决方案1】:

    你可以使用join:

    WITH xxx AS (
        SELECT array_agg(DISTINCT mc.id) as liste_ids
        FROM mots_cles mc
        WHERE mc.mot ILIKE '%Test%'
    )
    SELECT a.titre, a.id
    FROM articles a JOIN
         xxx
         ON a.motscles && xxx.liste_ids::integer[];
    

    EXISTS:

    SELECT a.titre, a.id
    FROM articles a 
    EXISTS (SELECT 1
            FROM xxx
            WHERE a.motscles && xxx.liste_ids::integer[]
           );
    

    【讨论】:

    • “JOIN”解决方案就像一个魅力。谢谢!
    猜你喜欢
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2022-12-23
    相关资源
    最近更新 更多