在LEFT JOIN PHP MySQL CodeIgniter中选择最新一行

Roe*_*oel 2 php mysql codeigniter

我想要实现以下目标:我有两张桌子.调用其中一个表,调用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           |
Run Code Online (Sandbox Code Playgroud)

到目前为止,我做了这个查询,它似乎在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;
Run Code Online (Sandbox Code Playgroud)

然后,我想在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);
Run Code Online (Sandbox Code Playgroud)

这与我的MySQL查询有关吗?我在CodeIgniter中的实现是不正确的?都?我很感激你的建议!

Fuz*_*ree 6

您可以使用仅选择id每行最大行的连接条件char_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');
Run Code Online (Sandbox Code Playgroud)

或类似地使用派生表

$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')
Run Code Online (Sandbox Code Playgroud)