0

私は2つのテーブルを持っています:

news ->     
  id_news    
  title    
  body    
  date_created    
  image    
  category_id    

comments ->     
  id_comments    
  news_id    
  body    
  date_created

すべてのニュースを取得し、すべてのニュースのすべてのコメントをカウントし、そのクエリをビュー パーツに表示するクエリを作成するにはどうすればよいですか?

4

3 に答える 3

2
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
于 2012-12-03T16:43:06.357 に答える
1

カウントしているので、DRap のクエリに小さな変更を加える必要があります。

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
于 2012-12-03T17:31:12.100 に答える
0

これを 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');

この後、関数ごとに並べ替えを使用して、必要に応じて結果を並べ替えることができます。

于 2015-11-20T10:52:15.703 に答える