简体   繁体   中英

Join top value from one SQL table to another SQL table

Ok guys I'm gonna do my best to explain this. I have a list of schools and a list of members from those schools. The application I'm building has users getting points for actions on the site. Now I have a leader board page that shows ever school, in order of total points but I'd also like to show the top individual scorer from that school...

So right now, using CodeIgniter ActiveRecord I'm doing this...

$this->load->database();
$this->db->select('school_name, points')->order_by('points', 'desc');
$query = $this->db->get( 'schools_final' );
return $query;

But I'd love to also show the top scorer from the user table from that specific school within this query if possible. I'd love to avoid making a sub-query in a foreach statement.

My tables look like this...

Schools...

id | school_name | points

Users...

id | first_name | last_name | school_id | points

I don't know how to write in CI but you have to use sub-query. The simple query for this purpose in mysql would be { select * from user,school where user.school_id = school.id and user.points = (select max(user.points) from user where user.school_id = school.id) group by school_id } I am sure you would find some way through in CI.

if im not getting wrong you question then your desired result will give you this query in CI Hope so

$query=$this->db->query("SELECT
  school_name.school_name AS School_Name,
  school_name.points      AS Total_point,
  users.first_name        AS Top_Scorer,
  users.points            AS Total_Point
FROM school_name
  LEFT JOIN users
    ON users.school_id = school_name.id
GROUP BY (users.school_id)
ORDER BY school_name.points,users.points DESC");
                return $query->result();

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