简体   繁体   English

基于Rails关系导出Postgres表

[英]Export postgres table based on rails relation

I have a user table that I can easily export with postgres by doing 我有一个用户表,可以通过以下操作轻松地使用postgres导出

\copy users to 'tmp/users2015.csv' csv header

My users has_many questions, and I'm wondering if there's a way I can export just the users who have asked a question. 我的用户有很多问题,我想知道是否有一种方法可以仅导出提出问题的用户。 The problem is here's no column in my users table that represents the number of questions a user has asked, so I don't think I can do this. 问题是我的用户表中没有列,该列代表用户提出的问题数量,因此我认为我无法做到这一点。 Is there any possible way or a different approach? 有没有可能的方法或其他方法? I really care about just knowing how many users have asked questions, so I could also export my questions table, and possibly filter out questions that have been asked by the same user? 我真的很在乎只知道有多少用户提出了问题,所以我也可以导出我的问题表,并可能过滤出同一用户提出的问题?

You can execute the same select query that the has_many relationship uses and use that to write to a file. 您可以执行has_many关系使用的相同选择查询,并使用该查询将其写入文件。

Copy (Select * From users where <some condition>) To '/tmp/test.csv' With CSV

See Save PL/pgSQL output from PostgreSQL to a CSV file for more info. 有关更多信息,请参见将PostgreSQL的PL / pgSQL输出保存到CSV文件

您应该向user表中另外导出一个表,该表包含一个名为“ question表”的belongs_to字段,以“ tmp / question2015.csv” CSV格式导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM