[英]I am joining three table but i want to use values of one of these tables for other two tables separately
I have 3 Tables Questions, Answers and Comments where there are multiple answers to the same question and many comments to a single answer. 我有3个表格问题,答案和评论,其中同一问题有多个答案,而单个答案有很多评论。
I want to show who answered the question and who commented to that answer. 我想展示谁回答了这个问题,以及谁评论了这个答案。
As well i want to show the user who replied and users who commented on the same answer. 我也想向用户显示回复的用户和对相同答案发表评论的用户。
So please help me to join the same user table twice in both tables answers and comments. 因此,请帮助我在表答案和注释中两次加入同一用户表。
Table: questions: id, text, user_id(fk) 表:问题:ID,文本,user_id(fk)
Table: answers: id, que_id(fk), user_id(fk), text 表格:答案:id,que_id(fk),user_id(fk),文本
Table: comments: id, ans_id(fk), user_id(fk), text 表格:注释:id,ans_id(fk),user_id(fk),文本
Table: users: id, name 表:用户: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();
My problem is that: 我的问题是:
I am getting the same user for all comments. 我正在所有评论中使用同一用户。
I want different commentator for different comments. 我想要不同的评论者来发表不同的评论。
If you are going to join the same table twice you should use a different name: 如果要两次连接同一张表,则应使用其他名称:
TESTED TESTED
$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();
If you noticed i used a different name for each join and used that name to get the related data, so if you want the user name for the answer you'd use UA.name
and if you want it for the comment you'd user UC.name
, and it gives you all the flexibility you need. 如果您发现我为每个UA.name
使用了一个不同的名称,并使用该名称来获取相关数据,那么如果您要使用答案的用户名,请使用UA.name
,如果要使用它作为注释的用户,请使用UC.name
,它为您提供了所需的所有灵活性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.