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条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?