User table:
userid | first_name | last_name |email |Password
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
Connection Table
con_id | userid | connected_with |date
1 | 1 | 2 |2015-04-26
2 | 1 | 3 |2015-04-26
3 | 4 | 1 |2015-04-26
I want to make query to find connection of userid 1. In this 1 userid is connected with 2, 3, and also 4 so how can I find connection of userid 1
You can get your answer from here.
MySql Query.
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();
Like you said in comment, you have two foreign keys userid
& connected_with
, you can use union to combine both query result. First query you find the connection where Connection.userid=1
. Second query you find the connection where Connection.connected_with=1
. Then combine both result.
See the code below
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();
Output
+--------------------------+
| Connection for User ID 1 |
+--------------------------+
| 4 |
| 2 |
| 3 |
+--------------------------+