2014-11-02 123 views
1

我试图实现以下功能: 我有两个表。其中一个表称为characters,另一个表称为experience。现在我想打印所有characters的列表,并将experience中的最新行链接到它。添加到characters中的那些行中,在experience中没有一行应该仍然显示。在LEFT JOIN中选择最新的一行PHP MySQL CodeIgniter

这里是表格和所需输出的示例。

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; 

然后,我想在笨实现这一点,但这就是它出了问题。 以下是我现在所拥有的内容,它填写了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中的实现是否不正确?都? 我很感激每一点建议!

+0

请检查什么SQL查询CI生成(使用'$ this-> db-> last_query()',我猜)。那么让我们看看,如果有任何区别。 – 2014-11-02 01:18:08

+0

生成的查询是正确的,** ITS A TYPO **'$ this-> db-> select('c.name,e1.exp');'应该是'$ this-> db-> select('c。名称,e1.experience');'因为**没有这样的栏目叫exp,它的经验** – 2014-11-02 05:25:20

回答

4

您可以使用连接条件,只选择最多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'); 

或类似使用派生表

$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') 
+0

这个作品就像一个魅力!非常感谢。 – Roel 2014-11-02 09:52:05

1

罗埃尔可以使用和方法来查找结果。在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(); 

希望它可以帮助