Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am stuck on one query in mysql

Tags:

php

mysql

I am stuck on one query in mysql.

I want to fetch most recent comment from the table

  • the comment should be most recent comment on the blog
  • the blogs should be latest 3 blogs.
  • display comment & blog only if their status is Enabled

records should be like this
enter image description hereenter image description hereenter image description here Table Structure for the table the table blog


  
blog_id int - primary (auto increment)
blog_title       -varchar
blog_desc        -varchar
blog_image       -varchar
blog_tags        -varchar
tot_comments     -int
blog_creater     -varchar
blog_create_date -datetime
blog_status      -enum ('Enable','Disable')

table structure for the table blog_comment


comment_id       -int (auto increment)  
fk_blog_id       -int  
comment          -varchar  
comment_by       -varchar  
email            -varchar  
comment_date     -datetime  
comment_status   -enum ('Enable','Disable')

And below is query written by me, but the result I am getting is wrong.

SELECT b.blog_title,b.blog_image, bc.*
FROM blog_comments  bc, blog b
WHERE bc.comment_status='Enable'
AND b.blog_status='Enable'
AND b.blog_id=bc.fk_blog_id
GROUP BY bc.fk_blog_id    
ORDER BY bc.comment_date DESC 
LIMIT 0,3

Output


enter image description here

like image 964
Alpesh Trivedi Avatar asked Feb 07 '13 10:02

Alpesh Trivedi


2 Answers

for this the easy solution will be execute 2 query for your result . first query get blog post result

$db_blog="select blog_id,blog_title from blog where blog_ststus='Enable'";
$que=mysql_query($db_blog); 
while($row=mysql_fetch_object($que))
{
    echo $row->blog_title;
    $db_comment="select comment from blog_comments where fk_blog_id=".$row->blog_id." and comment_status='Enable' order by comment_date desc";
    $quec=mysql_query($db_comment);
    while($comment=mysql_fetch_object($quec))
    {
         echo $comment->comment;
    }
}
like image 110
Ripa Saha Avatar answered Oct 19 '22 13:10

Ripa Saha


Try this:

SELECT * FROM blog_comments  bc, blog b
WHERE `bc.comment_status`='Enable'
AND `b.blog_status`='Enable'
AND `b.blog_id`=bc.fk_blog_id
ORDER BY `bc.comment_date` DESC LIMIT 1;

Try a simpler one:

SELECT * FROM `blog_comment` WHERE 'blog_status'='Enable' AND 'blog_id'='$blogidherefromtitle' ORDER BY 'comment_date' DESC LIMIT1
like image 42
devWaleed Avatar answered Oct 19 '22 12:10

devWaleed