用户表:
userid | first_name | last_name | email |密码
1 | Tom | cruise |tom@gmail.com |d41d8cd98f00b204e9800998ecf8427e
2 | Tamera | Manzer |Tame@yahoo.com|d41d8cd98f00b204e9800998ecf8427e
3 | Vergie | Manzer |Vere@live.com |d41d8cd98f00b204e9800998ecf8427e
4 | Elmo | Milano |elmo@live.com |d41d8cd98f00b204e9800998ecf8427e
连接表
con_id | userid | connected_with | date
1 | 1 | 2 |2015-04-26
2 | 1 | 3 |2015-04-26
3 | 4 | 1 |2015-04-26
我想查询以查找用户标识1的连接。在这1个用户标识与2,3连接,以及4如何找到用户标识1的连接
答案 0 :(得分:2)
你可以从这里得到答案。
MySql查询。
SELECT Connection.connected_with, Connection.date
FROM Connection
JOIN User ON User.userid = Connection.userid
WHERE Connection.userid =1
Codeigniter Active Record
$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
,您可以使用union来组合查询结果。首先查询您找到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 Active Record
// 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 |
+--------------------------+