lava done
lava done

Reputation: 27

How can i get one table id values to another table

I have a two tables in my database. One is "blog" second is "comment".

Blog table have this structure id, title, text, writer_id, created_at, updated_at Comment table have this structure id, blog_id, text, commenter_id, created_at, updated_at

I want to get id value from blog table as in comment table in the form of blog_id . How can i get the same value.

Example:

One blog posted. blog table have these values. id: 1 title: hi i m blogger text: how are you writer_id: 5 (same User id) created_at:25 feb updated_at: 25 feb Blog posted . One commenter comes and comment on this post. Value should be comes as like this in comment table id=1 blog_id:1 text: ok i know created_at:25 feb updated_at: 25 feb

id of blog table and blog_id of comment table should be same. How can i do this with query or php code?.

Upvotes: 0

Views: 96

Answers (2)

vibhor Bhatnagar
vibhor Bhatnagar

Reputation: 25

  • First of all you have to put foreign constraint that the value of column "Blog_Id" in table comment should always be from table "blog"

  • select * from blog bg inner join comment cm on cm.blog_id = blog.id this is the query for retrieving what you want.

Upvotes: 0

Vipin Jain
Vipin Jain

Reputation: 3756

Try This Query

SELECT b.id, c.`text`,..... FROM blog b
LEFT JOIN comment c
ON b.id = c.blog_id 
ORDER BY commenter_id DESC ;

if you want for perticular blog so add WHERE CONDITION

 SELECT b.id, c.`text`,.... FROM blog b
    LEFT JOIN comment c
    ON b.id = c.blog_id 
    b.id = 'Your ID'
    ORDER BY commenter_id DESC ;

Upvotes: 1

Related Questions