Posts

Showing posts with the label join

Optimize with joins, order, distinct on current active records / sql query

Optimize with joins, order, distinct on current active records / sql query I am using ruby on rails 4 and postgres currently, and making distinct and sorting as in the code below. I just have a feeling is not right and not optimized because it seems to be doing all this with an array. How could I combine this all into one activerecords query ? ads1 = Advertisement.where(property_id: nil) .where(target_address_city: [property.address_city, ""], target_address_state: [property.address_state, ""], target_address_country_id: property.address_country_id) # return advertisement belongs to the property ads2 = management.property.advertisements #combine both results combine_ads = ads1 + ads2 #remove ads duplicate uniq_ads = combine_ads.uniq { |ads| ads.id} # sort by created_at desc uniq_ads = uniq_ads.sort_by { |ads| -ads[:id]} # do pagination final_ads = uniq_ads.paginate(:page => pa...

SQL - query tables related in two different ways

SQL - query tables related in two different ways Imagine I have a MySQL database for managing a library, and I want to know about all members that have either borrowed or reserved it. I am looking for a single query, sorted by book ID. The tables are book, borrow, reserve and member. Both the borrow and reserve tables contain a book ID and member ID. I only want one unique pair of book ID and member ID in the result. This means these cases need to be deduplicated a member reserved a book and borrowed it also a member borrowed or reserved the book multiple times Can anyone help with this? please show us sample table structure with data in it. – Mohit Kumar Jul 1 at 4:03 Will make an SqlFiddle – Ben E. Jul 1 at 4:20 ...