英文:
Hi - I am creating a new table that needs 72 columns named mycount-1 to mycount-72 all of type integer
问题
我认为,在初始创建时,不必明确指定每个列名,而是可以使用一个带有递增值的循环,将其连接到"mycount-",然后传递给add column命令。或者也可以通过generate-series命令实现这一目标。
我不清楚如何实现这一点,也不知道最佳实践是什么,我找不到任何示例。
如果你能指导我到一个有帮助的讨论帖子或一些代码,那将非常棒。
英文:
Rather than explicitly state each column name in the initial create I am thinking that I should be able to have a loop with an incremental value which concatenates to "mycount-" then feeds into add column command. Alternatively could this be achieved through a generate-series command.
I have no idea what is or what's best practice to achieve this and I cant find any examples that do this.
if you could point me in the right direction of a thread that helps or some code that would be wonderful.
答案1
得分: 1
关于可疑的设计选择的评论应首先考虑。
话虽如此,您确实可以在通用语句中创建这样的表格,利用 psql
的 \gexec
实用程序。
思路是创建一个包含要执行的命令的字符串,并在查询后添加 \gexec
以运行它。
由于您有多列,您可以同时调用 generate_series
并将其输出与列名连接成单行。
SELECT 'create table test_rec (id integer, ' || string_agg('mycount_' || i || ' integer', ', ') || ');'
FROM generate_series(1,5) g(i);\gexec
另一方面,我个人认为对于这类任务,更高效的做法是打开 Excel 或类似的应用程序,拖动一个数字列表,与固定文本连接,复制-粘贴-完成。
英文:
The comments about the questionable design choice should be considered first.
That being said, you can indeed create such table in a generic statement, making use of psql
\gexec
utility.
The idea is to create a string containing the command to be executed, and to run it by appending \gexec
after the query.
Since you have multiple column, you can at the same time call generate_series
and concatenating its output with the column name into a single row.
SELECT 'create table test_rec (id integer, ' || string_agg('mycount_' || i || ' integer',', ') ||');'
FROM generate_series(1,5) g(i);\gexec
On the other hand, I personally find it more efficient for these kind of tasks to open Excel or alike, drag a number list, concatenate with a fixed text, copy-paste-done.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论