简体   繁体   中英

Insert records and update count in single query postgresql 9.6

I have two tables users and products . I'm inserting 20,000 records in one query but again i want to save the products count in the products_count attribute in users table into the same transaction. Also if there are any deletions of products for a user then it also needs to update the count.

This is how i'm inserting 20k records at once:

product_ids.each { |product_id| attrs << "('#{product_id}','#{user_id}','#{Time.now.utc}')" }
products_sql = "INSERT INTO products(product_id, user_id, created_at) VALUES #{attrs.join(', ')}"
ActiveRecord::Base.connection.execute(products_sql)

This is happening successfully. But how can i update the count into users table using the same query if possible?

One way is that i just use Rails update method to update the count.

At the end of your update you can execute a query to recalculate your product count. Something like

update
  users
set
  users.product_count=(select count(products.id) from products where products.user_id=users.id)

I know you want it in the same query but below may accomplish what you are looking for. Use this after your initial insert

product_ids.each { |product_id| attrs << "('#{product_id}',' {user_id}','#{Time.now.utc}')" }
products_sql = "INSERT INTO products(product_id, user_id, created_at) VALUES #{attrs.join(', ')}"
ActiveRecord::Base.connection.execute(products_sql)

product_count = product_ids.size
users_sql = "INSERT INTO users(product_count) VALUES #{product_count}"
ActiveRecord::Base.connection.execute(users_sql)

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