Good afternoon, there is a problem with sampling data from MYSQL. I am writing a site for ranking companies and came across a similar problem.

About the problem: There are 2 tables. 2 - companys and the second fileds

Table companys - has columns of which we need only id Table fileds - has columns comp_id, rating

Each company has 5 survey fields in fileds and is linked to the companys (Company).

There is a MYSQL query where JOIN is outputting data from 2 tables, you need to get not 5 results from each company, but a total amount of rating 5 fields under one id.

Sample Request without summation:

SELECT client.companys.id, client.fileds.rating FROM client.companys INNER JOIN client.fileds ON client.companys.id = client.fileds.comp_id Order by rating desc 

And the screen attach the result. query result

  • one
    It is not clear why the query generally needs the companys table, if only the id is needed, which is already in the fields. select comp_id, sum(rating) from fields group by comp_id - Mike

1 answer 1

You can do the following:

 SELECT client.companys.id, SUM(client.fileds.rating) AS rating FROM client.companys INNER JOIN client.fileds ON client.companys.id = client.fileds.comp_id GROUP BY client.companys.id ORDER BY rating DESC 
  • Thank you worked. - Alex Mixayelovich Sokolov