用户表:
用户ID |名字 |姓氏 |电子邮件 |密码
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 |用户 ID | connect_with |日期
1 | 1 | 2 |2015-04-26
2 | 1 | 3 |2015-04-26
3 | 4 | 1 |2015-04-26
我想查询以查找用户 ID 1 的连接。在这个用户 ID 1 与 2、3 和 4 连接时,我怎样才能找到用户 ID 1 的连接
最佳答案
您可以从这里得到答案。
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
,您可以使用 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 事件记录
// 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 |
+--------------------------+
关于php - 查询从名为 user 和 connection 的两个表获取连接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29881202/