2013-03-17 69 views
1

有2個表:的MySQL從users表中加入2個user_ids連續

orders: 
id requester_id supplyer_id status 
1 423   1   reserved 
2 500   1   supplied 
3 222   2   reserved 
... 

users 
id username register_date 
1  admin  2012-01-01 
2  smith  2013-01-01 
... 
423 John  2012-10-11 
500 Doe  2012-12-11 
222 name  2012-10-13 
... 

我想加入這兩個表,並得到這個結果

id requester_username supplier_username status 
1 John     admin    reserved 
2 Doe     admin    supplied 
3 name     smith    reserved 

實際上,我可以加入這些使用活動記錄表所示:

$this->db->select('orders.*,users.username') 
    ->from('orders') 
    ->join('users','users.id = orders.requester_id') 
    ->get()->result(); 

但我不知道如何讓supplier username在同一時間。

回答

0

嘗試添加第二個JOIN:

$this->db->select('orders.*,requesters.username,suppliers.username') 
    ->from('orders') 
    ->join('users AS requesters', 'requesters.id = orders.requester_id') 
    ->join('users AS suppliers', 'suppliers.id = orders.supplier_id') 
    ->get()->result(); 
0

在MySQL您的查詢應該是這樣的 -

Select a.id, b.username, c.username, a.status 
from orders a, users b, users c 
where 
a.requester_id = b.id 
And 
a.supplyer_id = c.id 

感謝