简体   繁体   English

将一个SQL表的最高值连接到另一SQL表

[英]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... 所以现在,我正在使用CodeIgniter ActiveRecord执行此操作...

$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. 我很想避免在foreach语句中进行子查询。

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. 我不知道如何用CI编写,但是您必须使用子查询。 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. 为此,在mysql中,简单的查询是{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我相信您会在CI中找到一些方法。

if im not getting wrong you question then your desired result will give you this query in CI Hope so 如果我没有弄错您的问题,那么您希望得到的结果将在CI Hope中为您提供此查询,因此

$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM