How can I do this as 1 database query?

Cache

I have a query that looks in the USER table to find the top 9 affiliates based on the frequency of their affiliate code.

affs = User.group(:affiliate).limit(9).count.sort_by{|i,j|-j}
(0.6ms)  SELECT  COUNT(*) AS count_all, affiliate AS affiliate FROM "users"  GROUP BY affiliate LIMIT 9
 #=> [["ACE5", 5], ["2YY", 3], ["MB7", 2], ["GB2", 2], ["GHCYM", 1], ["L6EOC", 1], ["15F2", 1], ["R0TK", 1], ["DSB", 1]] 

Now I take this result and I enumerate over it to get the row corresponding to the user.

affs.map do |aff|
  user = User.find_by(qcode: aff.first)
  [user.avatar.url(:thumb), user.name.match(/\w*/)[0], aff.first, aff.last]
end

 #LOG OUTPUT
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = 'ACE5' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = '2YY' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = 'GB2' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = 'MB7' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = 'L6EOC' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = '15F2' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = 'R0TK' LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."qcode" = 'DSB' LIMIT 1

Running this query 9 times seems very redundant. How can I optimize this into 1 or 2 database queries?

Example USERS table DB Schema:

id | email              | name         | qcode  | affiliate
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
25 | [email protected]     | Ken Lu       | DSB    | L6EOC         
26 | [email protected]     | Brains Bruk  | AJ8U   | DSB           
27 | [email protected]    | Joan Hu      | K9UE   | DSB               

From the above example. "Ken Lu" is affiliate DSB and he is responsible for signing up ID 26 and ID 27. So the above aff query would produce:

 #=> [["DSB", 2], ...] 
khampson

To get the user table information for all 9 affiliates at once, you can drop down into raw SQL.

From what I can infer of your schema from the code above, something like this should work (you may need to tweak it a bit if your schema differs from what I inferred; not tested since I don't have your data nor a Rails setup handy):

WITH top_affiliates AS
(
    SELECT  COUNT(*) AS count_all, affiliate AS affiliate
    FROM users
    GROUP BY affiliate
    ORDER BY count_all
    LIMIT 9
)
SELECT *
FROM top_affiliates AS t
JOIN users AS u ON (t.affiliate = u.qcode)
ORDER BY count_all

Note that the JOIN assumes that t.affiliate = u.qcode will provide a unique mapping between the tables (based on the resulting SQL from when you were iterating over the map, this seemed like a fair assumption). If it's not unique, though, you would need to add additional parameters in the JOIN such that the mapping is unique, else you would get additional rows in the result that you wouldn't want.

If you're using ActiveRecord, you can use connection.execute on the model containing this information, and pass the above SQL in as a string (or assign it to a variable first and pass that in).

Edit in response to comment from OP:

@f1f5: The WITH query defines what's called a CTE, which is essentially a temp table scoped to the query itself as opposed to the connection. I can then use that CTE in queries underneath the WITH, which is what I'm doing above. Basically, the WITH query is taking the place of your User.group(:affiliate).limit(9).count.sort_by{|i,j|-j} code and then using the results inline to pull the relevant user records.

Edit in response to schema info from OP:

So, yes, I think my code above will do what you want. Here's an sqlfiddle I created with the schema data, query, and result.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

How can I do this LINQ query in BreezeJS?

분류에서Dev

How do I create a SQLite query and embed it into an SQLite Database

분류에서Dev

I can not do this query without nested select

분류에서Dev

How can I do a "where in" type query using ember-data

분류에서Dev

How do I repair malformed Banshee database?

분류에서Dev

How can I Join Two Query

분류에서Dev

How can I improve the performance of this slow query

분류에서Dev

How can I limit the results in a PagingAndSortingRepository @Query?

분류에서Dev

How can i use data in an array in a query

분류에서Dev

How can I restrict a LINQ Query?

분류에서Dev

I am trying to write a query but can seem to think of a way to do it

분류에서Dev

how can I do this with the variables in lua?

분류에서Dev

How can I do customize category - android

분류에서Dev

How can I do subdirectory manipulation in shell?

분류에서Dev

How can I import a database using command line?

분류에서Dev

How can I change properties of FK in SQL Server database project?

분류에서Dev

How can I host a single MySQL database on multiple servers?

분류에서Dev

How can I set background image from database in css?

분류에서Dev

How can i insert return value to mysql database in python?

분류에서Dev

How can I sync my data from an external database in Rails?

분류에서Dev

How can I effectively save a tree structure in a database?

분류에서Dev

Using Laravel Migrate how can I refresh a single database?

분류에서Dev

How can I get total user in a group from database by PHP

분류에서Dev

How do I load the list of a ComboBox from the database?

분류에서Dev

How do I send a time to a MySql database with PHP?

분류에서Dev

How do I display database items separated by an ID in Coldfusion?

분류에서Dev

how do i search for an entry in mongodb database using java in netbeans?

분류에서Dev

How do I skip a listview row when saving into the Database?

분류에서Dev

How can I cast NextJS router.query as a number?

Related 관련 기사

  1. 1

    How can I do this LINQ query in BreezeJS?

  2. 2

    How do I create a SQLite query and embed it into an SQLite Database

  3. 3

    I can not do this query without nested select

  4. 4

    How can I do a "where in" type query using ember-data

  5. 5

    How do I repair malformed Banshee database?

  6. 6

    How can I Join Two Query

  7. 7

    How can I improve the performance of this slow query

  8. 8

    How can I limit the results in a PagingAndSortingRepository @Query?

  9. 9

    How can i use data in an array in a query

  10. 10

    How can I restrict a LINQ Query?

  11. 11

    I am trying to write a query but can seem to think of a way to do it

  12. 12

    how can I do this with the variables in lua?

  13. 13

    How can I do customize category - android

  14. 14

    How can I do subdirectory manipulation in shell?

  15. 15

    How can I import a database using command line?

  16. 16

    How can I change properties of FK in SQL Server database project?

  17. 17

    How can I host a single MySQL database on multiple servers?

  18. 18

    How can I set background image from database in css?

  19. 19

    How can i insert return value to mysql database in python?

  20. 20

    How can I sync my data from an external database in Rails?

  21. 21

    How can I effectively save a tree structure in a database?

  22. 22

    Using Laravel Migrate how can I refresh a single database?

  23. 23

    How can I get total user in a group from database by PHP

  24. 24

    How do I load the list of a ComboBox from the database?

  25. 25

    How do I send a time to a MySql database with PHP?

  26. 26

    How do I display database items separated by an ID in Coldfusion?

  27. 27

    how do i search for an entry in mongodb database using java in netbeans?

  28. 28

    How do I skip a listview row when saving into the Database?

  29. 29

    How can I cast NextJS router.query as a number?

뜨겁다태그

보관