[英]Select latest row in LEFT JOIN PHP MySQL CodeIgniter
我想要實現以下目標:我有兩張桌子。 其中一個表稱為characters
,另一個表稱為experience
。 現在我想要打印所有characters
的列表,並將最新的experience
行鏈接到它。 仍然會顯示添加到沒有experience
行的characters
行。
這是表和所需輸出的示例。
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')
Roel你可以使用sum方法來查找結果。 在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
當您在codeigniter中使用時,您可以嘗試以下方法: -
$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();
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.