gpt4 book ai didi

sql - 如何缩进基于 "depth"的查询输出?

转载 作者:行者123 更新时间:2023-11-29 14:23:01 25 4
gpt4 key购买 nike

想象一下这样的表格:

create table test (depth integer, name text);

添加一些行:

insert into test (depth, name)
values (0, "no indent"), (1, "single indent"), (2, "double indent");

现在,根据如下所示的 depth 参数创建输出:

no indent
single indent
double indent

本例中的缩进是 4 个空格(但可以更改为任何有趣的缩进,例如制表符)。

我的直觉想要做这样的事情:

select '    ' * depth || name from test order by depth;

然而,这在 Postgres 中爆炸了。像这样的字符串乘法在 Python 中按预期工作。但是,我不熟悉 Postgres 中的等效操作。其他数据库实现也会很有趣。

最佳答案

使用lpad():

select lpad(name, (4 * depth) + length(name), ' ')
from test
order by depth;

repeat()加连接:

select repeat('_', 4 * depth) || name
from test
order by depth;

http://www.postgresql.org/docs/current/static/functions-string.html

关于sql - 如何缩进基于 "depth"的查询输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15442649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com