我有两张桌子:
news ->
id_news
title
body
date_created
image
category_id
comments ->
id_comments
news_id
body
date_created
如何编写查询以获取所有新闻,计算每条新闻的所有评论并在视图部分显示该查询?
我有两张桌子:
news ->
id_news
title
body
date_created
image
category_id
comments ->
id_comments
news_id
body
date_created
如何编写查询以获取所有新闻,计算每条新闻的所有评论并在视图部分显示该查询?
select
N.ID_News,
N.Title,
N.Body,
N.Date_Created,
N.Image,
N.Category_ID,
count(C.ID_Comments) CommentCount
from
News N
LEFT JOIN Comments C
on N.ID_News = C.News_ID
group by
N.ID_News
order by
whatever column(s) are important to you
由于我们正在计数,我们需要对 DRap 的 Query 做一个小改动:
select
N.ID_News,
N.Title,
N.Body,
N.Date_Created,
N.Image,
N.Category_ID,
count(C.ID_Comments) CommentCount
from
News N
LEFT JOIN Comments C
on N.ID_News = C.News_ID
order by
whatever column(s) are important to you
那只会给你一个结果..由于该查询缺少 group by 语句,我建议将该查询更改为:
select
N.ID_News,
N.Title,
N.Body,
N.Date_Created,
N.Image,
N.Category_ID,
count(C.ID_Comments) CommentCount
from
News N
LEFT JOIN Comments C
on N.ID_News = C.News_ID
group by
N.title
order by
whatever column(s) are important to you
以 Active Record 格式写下来是这样的:
$this->db->select('N.ID_News, N.Title, N.Body, N.Date_Created, N.Image')
$this->db->select('N.Category_ID, count(C.ID_Comments) AS CommentCount');
$this->db->from('News AS N');
$this->db->join('commentas AS C', 'N.ID_News = C.News_ID', 'left');
$this->db->group_by('N.title');
在此之后,您可以使用按功能排序,根据需要对结果进行排序。