0

My aim is to write the last modified date (lastmod) of my approved articles for my sitemap.xml file. There are 2 possibilities for this data.

  1. If article has no approved comment, then lastmod is the approval date of the article.
  2. If article has at least 1 approved comment, then lastmod is the approval date of the last approved comment of related article.

after asking php unsuccessful while loop within prepared statements question and reading answers, I decided

  1. not to use loop within prepared for this case
  2. add col_article_id column to my comments table which shows the related article's id in article table
  3. and try to solve my case with a smarter mySQL query

I have 2 tables:

  1. articles
  2. comments (comments.col_article_id links the comment to the related article)

After I tried query below,

select tb_articles.col_approvaldate, tb_comments.col_approvaldate
from tb_articles, tb_comments
where tb_articles.col_status ='approved' AND tb_comments.col_status ='approved' AND tb_articles.col_id=tb_comments.col_article_id

my problems are:

1 - I need someway as if it was allowed in mysql syntax that select max( tb_articles.col_approvaldate, tb_comments.col_approvaldate)

2 - If I have n approved articles without any approved comment and m approved articles with approved comment(s), then I should have n+m result rows with 1 column at each row. But currently, I have m rows with 2 columns at each row.

So I'm aware that I'm terribly on wrong way.

I also searched "mysql newest row per group" keywords. But this the point I could arrived after all.

this is my 1st join experience. can you please correct me? best regards

4

2 回答 2

1

尝试这个:

select
    tb_articles.id,
    ifnull(
        max( tb_comments.col_approvaldate),
        tb_articles.col_approvaldate
    ) as last_approved
from tb_articles
left join tb_comments
    on tb_articles.col_id=tb_comments.col_article_id
    and tb_comments.col_status ='approved'
where tb_articles.col_status ='approved'
group by 1;
于 2013-04-29T03:01:33.237 回答
0

我是否正确理解tb_comments文章的记录是默认创建的?情况不应该是这样——如果没有评论,那里就不应该有记录。如果有,您输入的默认日期是什么?无效的?对我来说也tb_comments.col_status似乎是多余的 - 如果你有tb_comments.col_approvaldate那么它在那个日期被批准并且你根本不需要状态。

这个查询可能对你有用(AND如果我正确理解你的表结构,评论不应该改变事情):

SELECT 
    a.col_id AS 'article_id',
    IFNULL(MAX(c.col_approvaldate), a.col_approvaldate)
FROM 
    tb_articles a 
    LEFT JOIN tb_comments c ON a.col_id = c.col_article_id #AND c.col_status ='approved'
WHERE 
    a.col_status ='approved'
GROUP BY a.col_id
于 2013-04-29T02:53:02.873 回答