我试图实现以下功能: 我有两个表。其中一个表称为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中的实现是否不正确?都? 我很感激每一点建议!
请检查什么SQL查询CI生成(使用'$ this-> db-> last_query()',我猜)。那么让我们看看,如果有任何区别。 – 2014-11-02 01:18:08
生成的查询是正确的,** ITS A TYPO **'$ this-> db-> select('c.name,e1.exp');'应该是'$ this-> db-> select('c。名称,e1.experience');'因为**没有这样的栏目叫exp,它的经验** – 2014-11-02 05:25:20