cod*_*bly 9 postgresql row record subquery
如何从记录中提取值作为postgresql中的单个comuns
SELECT
p.*,
(SELECT ROW(id,server_id,format,product_id) FROM products_images pi WHERE pi.product_id = p.id LIMIT 1) AS image
FROM products p
WHERE p.company = 1 ORDER BY id ASC LIMIT 10
Run Code Online (Sandbox Code Playgroud)
代替
image
(3, 4, "jpeg", 7)
Run Code Online (Sandbox Code Playgroud)
我想拥有
id | server_id | format | product_id
3 | 4 | jpeg | 7
Run Code Online (Sandbox Code Playgroud)
有没有办法为每个产品只选择一个图像并直接返回列而不是记录?
试试这个:
create type xxx as (t varchar, y varchar, z int);
with a as
(
select row(table_name, column_name, (random() * 100)::int) x
from information_schema.columns
)
-- cannot cast directly to xxx, should cast to text first
select (x::text::xxx).t, (x::text::xxx).y, (x::text::xxx).z
from a
Run Code Online (Sandbox Code Playgroud)
或者,您可以这样做:
with a as
(
select row(table_name, column_name, (random() * 100)::int) x
from information_schema.columns
),
-- cannot cast directly to xxx, should cast to text first
b as (select x::text::xxx as w from a)
select
(w).t, (w).y, (w).z
from b
Run Code Online (Sandbox Code Playgroud)
要选择所有字段:
with a as
(
select row(table_name, column_name, (random() * 100)::int) x
from information_schema.columns
),
-- cannot cast directly to xxx, should cast to text first
b as (select x::text::xxx as w from a)
select
(w).*
from b
Run Code Online (Sandbox Code Playgroud)
你也可以这样做,但是当你可以删除ROW函数并从cte/derived表外部重新拾取它时,这使得使用ROW的整个练习变得毫无意义.我猜测OP的ROW来自一个功能; 他应该使用上面的代码,而不是以下代码:
with a as
(
select row(table_name, column_name, (random() * 100)::int)::xxx x
from information_schema.columns
)
select
(x).t, (x).y, (x).z
from a
Run Code Online (Sandbox Code Playgroud)
只需指定结构的组件:
SELECT a,b,c,(image).id, (image).server_id, ...
FROM (
SELECT
p.*,
(SELECT ROW(id,server_id,format,product_id) FROM products_images pi WHERE pi.product_id = p.id LIMIT 1) AS image
FROM products p
WHERE p.company = 1 ORDER BY id ASC LIMIT 10
) as subquery
Run Code Online (Sandbox Code Playgroud)
但无论如何,我会重新设计查询并使用联接而不是子条款。
SELECT DISTINCT ON (p.*) p.*,
p.id,pi.server_id,pi.format,pi.product_id
FROM products p
LEFT JOIN product_images pi ON pi.product_id = p.id
WHERE p.company = 1
ORDER BY id ASC
LIMIT 10
Run Code Online (Sandbox Code Playgroud)
但我相信您必须分别指定不同的所有 p 字段,以确保每个产品仅加载一张图像。