您可以从这里得到答案。
Read here
MySql 查询。
SELECT Connection.connected_with, Connection.date
FROM Connection
JOIN User ON User.userid = Connection.userid
WHERE Connection.userid =1
Codeigniter 活动记录
$this->db->select('connected_with', 'date');
$this->db->from('Connection');
$this->db->join('User', 'User.userid' = 'Connection.userid');
$this->db->where('userid', 1);
$this->db->get();
就像你在评论中说的,你有两个外键userid & connected_with,你可以使用联合来组合两个查询结果。首先查询你找到Connection.userid=1所在的连接。第二个查询你找到Connection.connected_with=1 所在的连接。然后合并两个结果。
请看下面的代码
SELECT Connection.userid AS 'Connection'
FROM Connection
JOIN User ON User.userid = Connection.connected_with
WHERE Connection.connected_with =1
UNION
SELECT Connection.connected_with
FROM Connection
JOIN User ON User.userid = Connection.userid
WHERE Connection.userid =1
Codeigniter 活动记录
// First Query
$this->db->select('connected_with', 'date');
$this->db->from('Connection');
$this->db->join('User', 'User.userid' = 'Connection.userid');
$this->db->where('userid', 1);
$query = $this->db->get();
$subQuery1 = $this->db->_compile_select();
$this->db->_reset_select();
// Second Query
$this->db->select('userid', 'date');
$this->db->from('Connection');
$this->db->join('User', 'User.userid' = 'Connection.connected_with);
$this->db->where('connected_with', 1);
$query = $this->db->get();
$subQuery2 = $this->db->_compile_select();
$this->db->_reset_select();
// Union
$this->db->from("($subQuery1 UNION $subQuery2)");
$this->db->get();
输出
+--------------------------+
| Connection for User ID 1 |
+--------------------------+
| 4 |
| 2 |
| 3 |
+--------------------------+