我有 3 个表问题、答案和评论,其中同一问题有多个答案,而单个答案有很多评论。
我想显示谁回答了问题以及谁对此答案发表了评论。
我还想显示回复的用户和对同一答案发表评论的用户。
因此,请帮助我在表答案和评论中两次加入同一个用户表。
表:问题:id、文本、user_id(fk)
表:答案:id、que_id(fk)、user_id(fk)、文本
表格:评论:id、ans_id(fk)、user_id(fk)、文本
表:用户:id、名称
$this->db->select('answers.id as aid,
answers.user_id as auser_id,
answers.text as atext,
comments.id as cid,
comments.user_id as cuser_id,
comments.text as ctext,
users.id as uid,
users.name as uname');
$this->db->from('answers');
$this->db->join('users','answers.user_id = users.id', 'left');
$this->db->join('ans_comments','answers.id = comments.ans_id', 'left');
$this->db->join('users','comments.user_id = users.id', 'left');
$this->db->where('que_id','1');
return $this->db->get();
我的问题是:
I am getting the same user for all comments.
I want different commentator for different comments.
最佳答案
如果您要两次加入同一个表,则应该使用不同的名称:
已测试
$this->db->select('A.id AS A_id,
A.uid AS A_uid,
A.text AS A_text,
C.id AS C_id,
C.uid AS C_uid,
C.text AS C_text,
UA.id AS UA_id,
UA.name AS UA_name,
UC.id AS UC_id,
UC.name AS UC_name');
$this->db->from('answers AS A');
$this->db->join('comments AS C','C.aid = A.id', 'left');
$this->db->join('users AS UA','A.uid = UA.id', 'left');
$this->db->join('users AS UC','C.uid = UC.id', 'left');
$this->db->where('qid', 1);
$query = $this->db->get();
$result = $query->result_array();
如果您注意到我为每个连接使用了不同的名称,并使用该名称来获取相关数据,因此如果您想要答案的用户名,您可以使用UA.name
并且如果您希望使用 UC.name
来发表评论,它为您提供了所需的所有灵 active 。
关于mysql - 我正在加入三个表,但我想将其中一个表的值分别用于其他两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927096/