Skip to content

Instantly share code, notes, and snippets.

@trabianmatt
Created June 29, 2011 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trabianmatt/1054787 to your computer and use it in GitHub Desktop.
Save trabianmatt/1054787 to your computer and use it in GitHub Desktop.
# Uses 101 (also known as n + 1 where n = 100) queries
mergeTransactionsBad: ->
all_transactions = []
te_transactions = db.run "select * from te_transactions where member_id=1 order by posted_at DESC limit 100"
for transaction in te_transactions
network_transaction = db.run "select * from network_transactions where transaction_id=#{transaction.id}"
transaction.member_id = network_transaction.id
all_transactions.push transaction
return all_transactions
# Uses 2 queries
mergeTransactionsGood: ->
all_transactions = {} # Make sure this is an ordered data store -- Redis sorted sets serve this use case quite well
te_transactions = db.run "select * from te_transactions where member_id=1 order by posted_at DESC limit 100"
network_transactions = db.run "select * from network_transactions where member_id=1 order by posted_at DESC limit 100"
for te_transaction in te_transactions
all_transactions[transaction.id] = te_transaction
for network_transaction in network_transactions
transaction = all_transactions[network_transaction.id]
transaction.member_id = transaction
all_transactions[transaction.id] = transaction
return all_transactions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment