我正在努力实现以下目标:我有两张桌子。其中一个表被称为characters
,而另一个表则被称为experience
。现在我想打印一个所有characters
的列表,并将experience
中的最新一行链接到它。除此之外,characters
中没有experience
行的行仍应显示。
这里是表格和所需输出的示例。
characters
id | name |
----------------|
1 | TestChar |
2 | NewChar |
3 | OldChar |
experience
id | char_id | experience |
------------------------------|
1 | 1 | 683185858 |
2 | 2 | 85712849 |
3 | 1 | 687293919 |
4 | 1 | 794812393 |
output
name | experience |
---------------------------|
TestChar | 794812393 |
NewChar | 85712849 |
OldChar | NULL |
到目前为止,我做了这个查询,它似乎在MySQL 中工作
SELECT c.name, e1.experience
FROM characters c
LEFT JOIN experience e1 ON e1.char_id = c.id
LEFT JOIN experience e2 ON e1.char_id = e2.char_id AND e2.id > e1.id
WHERE e2.id IS NULL;
然后,我想在CodeIgniter中实现这一点,但这就是问题所在。以下是我现在所拥有的,它填充了c.name,但e1.exp仍然为空。
$this->db->select('c.name, e1.exp');
$this->db->from('characters as c');
$this->db->join('experience as e1', 'e1.char_id = c.id', 'left');
$this->db->join('experience as e2', 'e1.char_id = e2.char_id AND e2.id > e1.id', 'left');
$this->db->where('e2.id', NULL);
这与我的MySQL查询错误有关吗?我在CodeIgniter中的实现是否不正确?二者都我感谢你的每一点建议!
您可以使用一个联接条件,该条件只选择每char_id
最大id
的行。
$this->db->select('c.name, e1.exp');
$this->db->from('characters as c');
$this->db->join('experience as e1', 'e1.id = (select max(id) from experience as e2 where e2.char_id = e1.char_id)', 'left');
或者类似地使用派生表
$this->db->select('c.name, e1.exp');
$this->db->from('characters as c');
$this->db->join('(select max(id) max_id, char_id
from experience group by char_id) as t1', 't1.char_id = c.id', 'left')
$this->db->join('experience as e1', 'e1.id = t1.max_id', 'left')
Roel您可以使用sum方法来查找结果。在mysql中,它将是
SELECT c.name, SUM(e1.experience) as expsum
FROM characters c
LEFT JOIN experience e1 ON e1.char_id = c.id GROUP BY c.name
当你在代码点火器中使用时,你可以尝试以下操作:-
$this->db->select("c.name, SUM(e1.exp) as 'expsum'");
$this->db->from('characters as c');
$this->db->join('experience as e1', 'e1.char_id = c.id', 'left');
$this->db->group_by("c.name");
$this->db->get();
$query->results_array();
希望它能帮助