S.M_Emamian
S.M_Emamian

Reputation: 17383

using join a table to itself and join another table

I have two tables like below pictures :

users table :

enter image description here

offer_comments

enter image description here

offer_comments table stores comments and answer to comments. by using below function I can get comments and answer to comments depending on $id.

function getCommentsAnItem($id){

    mysql_query("SET CHARACTER SET utf8");
    $result_comments = mysql_query("select e.comment as comment,m.comment as answer_to_comment 
    from offer_comments e 
    inner join offer_comments m on e.id = m.quet 
    where e.offer_id=$id and e.confirm=1");
    $comments = array();
    while($a_comment=mysql_fetch_object($result_comments)){

        $comment = array(
        'comment'=>$a_comment->comment,
        'answer'=>$a_comment->answer_to_comment
        );
        array_push($comments,$comment);
    }

    return $comments ;
}

How do I can get name and family from users table depending on user_id in offer_comments table ?


updated:

admin is where user_id equal = 1 .

user_id 14690 is a user and leaves a comment and admin answer to him.

enter image description here

in the users table : enter image description here

I would like to get an array of comments and answer to comments depending on $id :

"comment=>how a u ?","answer=> I am fine","comment.name=>name","comment.family=>family"

Upvotes: 0

Views: 32

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

Join your user table with your current query with offer_comments aliased as m so it will show the name and family of user who belongs to m.comment or the one who added m.comment,if you want to show the user of offer_comments aliased as e then join on e.user_id

SELECT 
  e.comment AS `comment`,
  m.comment AS answer_to_comment,
  u.name,
  u.family 
FROM
  offer_comments e 
  INNER JOIN offer_comments m 
    ON e.id = m.quet 
  INNER JOIN users s 
    ON s.id = m.user_id 
WHERE e.offer_id = $id 
  AND e.confirm = 1 

Upvotes: 2

Related Questions