简体   繁体   中英

Export postgres table based on rails relation

I have a user table that I can easily export with postgres by doing

\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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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