【发布时间】:2016-11-07 04:21:34
【问题描述】:
作为上一个问题的后续:
我有以下疑问:
SELECT row_number() OVER (ORDER BY t.id) AS id
, t.id AS "RID"
, count(DISTINCT a.ord) AS "Matches"
FROM tbl t
LEFT JOIN (
unnest(array_content) WITH ORDINALITY x(elem, ord)
CROSS JOIN LATERAL
unnest(string_to_array(elem, ',')) txt
) a ON t.description ~ a.txt
OR t.additional_info ~ a.txt
GROUP BY t.id;
这给了我正确的匹配,但现在array_content 的值需要是动态的,并且也是列值之一。
假设我正在使用聚合函数来获取查询中的数组内容:
SELECT row_number() OVER (ORDER BY t.id) AS id
, t.id AS "RID"
, array_agg(DISTINCT demo_a.element_demo) as array_values
, count(DISTINCT a.ord) AS "Matches"
, count(DISTINCT demo_a.ord) AS "Demo_Matches"
FROM tbl t
LEFT JOIN (
unnest(array_values) WITH ORDINALITY x(elem, ord)
CROSS JOIN LATERAL
unnest(string_to_array(elem, ',')) txt
) a ON t.description ~ a.txt
OR t.additional_info ~ a.txt
LEFT JOIN (
unnest("test1","test2"::varchar[]) WITH ORDINALITY x(element_demo, ord)
CROSS JOIN LATERAL
unnest(string_to_array(element_demo, ',')) text
) demo_a ON i.name ~ demo_a.text
GROUP BY t.id;
现在我需要用array_values 列代替未嵌套部分中定义的array_content。是否可以?
目前它给出了一个未定义列名的异常。
【问题讨论】:
-
为简单数组
{"test","test1"}添加的双重嵌套没有意义。单个unnest()已经取消嵌套所有要取消嵌套的... -
另外,您的两个 LEFT JOIN 子查询之间的代理 CROSS JOIN 几乎肯定是错误的。以鱼市为例:stackoverflow.com/questions/12464037/…
-
但是@Erwin 这两个左连接有不同的用途。
-
当然,你还在搞砸计数。 (我现在要睡觉了……)
-
是否可以像上述问题一样将选择查询中定义的列名引用到 LEFT JOIN 中
标签: sql arrays postgresql aggregate-functions unnest