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

标签 php mysql codeigniter

我正在努力实现以下目标: 我有两张 table 。其中一个表称为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')

关于php - 在 LEFT JOIN PHP MySQL CodeIgniter 中选择最新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694903/

相关文章:

php - SQL 连接返回错误结果

php - 获取精确的日期时间,包括毫秒照片从 php 中的图像文件中获取的时间

PHP 登录总是返回错误

php - 将给定时间设置为 00 :00:00 in PHP/MySQL

php - 使用 jquery/ajax 加载 php 页面以打开特定链接以在 Div 中显示页面

php - 为这些数据组织我的 MySQL 数据表的最佳方式是什么?

php - 使用ajax codeigniter php根据日期检索数据库值

php - 目标 [League\OAuth2\Server\Repositories\ClientRepositoryInterface] 在构建 [League\OAuth2\Server\AuthorizationServer] 时不可实例化

php - 计算用户的排名

mysql - #1242 - 子查询在 mysql 中返回多于 1 行