dptn69182 2014-11-02 00:52
浏览 174
已采纳

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

I am trying to achieve the following: I have two tables. One of the tables is called characters and the other one is called experience. Right now I want to print a list of all characters and linking the latest row in experience to it. Added to that rows in characters without a row in experience should still be shown.

Here an example of the tables and desired output.

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           |

So far, I made this query and it seems to work in 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;

Then, I want to implement this in CodeIgniter but that's where it goes wrong. The following is what I have right now, it fills in the c.name but the e1.exp remains empty.

$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);

Is this related to my MySQL query being wrong? Is my implementation in CodeIgniter incorrect? Both? I appreciate every bit of advice!

  • 写回答

2条回答 默认 最新

  • dongliyan9190 2014-11-02 01:28
    关注

    You can use a join condition that only selects the row the maximum id per 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');
    

    or similarly using a derived table

    $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')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀