简体   繁体   中英

mysql join 2 user_ids in a row from users table

There are 2 tables:

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 
...

I want to join these two tables and get this as a result

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

I can actually join these tables using active records like :

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

but I dont know how to get the supplier username at the same time.

Try adding a second 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();

In MySql Your query should be like -

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

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM