codeigniter order by who has max value in points列

x759pob2  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(277)

我的公司表列“rev”包含所有评级总和,我想根据评级订购

public function all_company($limit, $offset)
{
$query = $this->db
->select(['id','name'])
->from('company')
->order_by('MAX(rev)', 'desc')
->get();
return $query->result();
}

公司表结构

ID | Name | Rev
1   name1   65
2   name2   15
3   name3   96
ql3eal8s

ql3eal8s1#

您可以尝试此表结构并查询您的问题:
从公司中选择*;
从公司评级中选择*;

SELECT company.id, company.company_name, MAX(company_rating.rating)
FROM company
RIGHT JOIN company_rating ON company_rating.company_id = company.id
GROUP BY company.id
ORDER BY MAX(company_rating.rating) DESC

能否尝试使用ci活动查询:

$this->db->select('company.id, company.company_name, MAX(company_rating.rating)', false);
$this->db->from('company');
$this->db->join('company_rating c', 'company_rating.company_id = company.id', 'right');
$this->db->group_by('company.id'); 
$this->db->order_by('MAX(company_rating.rating)', 'desc');
$query = $this->db->get();
return $query->row();

还可以修改表结构,如

CREATE TABLE  `company` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `company_name`varchar(30),
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `company` (`company_name`) VALUES
('ABC'),
('XYZ');

CREATE TABLE  `company_rating` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int(11),
  `rating` int(11),
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `company_rating` (`company_id`,`rating`) VALUES
(1,2),
(1,4),
(1,5),
(2,4),
(2,7),
(2,10);

也可以参观这个http://sqlfiddle.com
输出如下:

id  company_name    rating 

1   ABC              5 

2   XYZ              10

我希望这会有帮助

相关问题