如何从记录中提取值作为 postgresql 中的单独列
如何从记录中提取值作为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
而不是
image
(3, 4, "jpeg", 7)
我想要有
id | server_id | format | product_id
3 | 4 | jpeg | 7
没有办法为每个产品仅选择一个图像并直接返回列而不是记录?
How can I extract the values from a record as individual comuns in postgresql
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
Instead of
image
(3, 4, "jpeg", 7)
I would like to have
id | server_id | format | product_id
3 | 4 | jpeg | 7
Is there any way of selecting only one image for each product and return the columns directly instead of a record?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试一下:
或者,您可以这样做:
选择所有字段:
您也可以这样做,但这使得使用 ROW 的整个练习变得毫无意义,因为您可以删除 ROW 函数并从外部重新选择它。 cte/派生表。我猜测OP的ROW来自一个函数;为此,他应该使用上面的代码,而不是下面的代码:
Try this:
Alternatively, you can do this:
To select all fields:
You can do this too, but this makes the whole exercise of using ROW a pointless one when you can just remove the ROW function and re-pick it up from outside of cte/derived table. I surmised the OP's ROW came from a function; for which he should use the codes above, not the following:
只需指定结构的组件:
但无论如何,我会重新设计查询并使用联接而不是子条款。
但我相信您必须分别指定不同的所有 p 字段,以确保每个产品仅加载一张图像。
Just specify the components of your struct:
But anyway, I would rework the query and use a join instead of a subclause.
But I believe you have to specify all the p-fields in the distinct separately to ensure just one image is loaded per product.
尝试一下,只需最少的修改即可在您现有的代码上工作(如果创建类型对您来说是最小的修改;-)
概念验证代码:
首先创建类型:
实际代码:
但我想您应该使用
GROUP BY' 和
MAX组合或使用
DISTINCT ON` 就像 Daniel 发布的那样Try this, will work on your existing code with minimal modification(if creating a type is a minimal modification for you ;-)
Proof-of-concept code:
Create type first:
Actual code:
But I guess you should tackle it with
GROUP BY' and
MAXcombo or use
DISTINCT ON` like what Daniel have postedhttps ://www.postgresql.org/docs/current/plpgsql-declarations.html#PLPGSQL-DECLARATION-ROWTYPES
所以,这段代码
可以工作
https://www.postgresql.org/docs/current/plpgsql-declarations.html#PLPGSQL-DECLARATION-ROWTYPES
So, this code
will work