简体   繁体   中英

Count comments to each recension?

I need someone to help me with this problem. My head doesn't want to think straight today.

So, i have a table named "recensions", and another named "comments". In each table, i have a column named "amne_id". This would make so i could connect the comments to the correct recension.

Now, on my first page, i simply get all the recensions with the code:

$rec = $this->db->get('recensions');

What i want is to count how many comments each recension has. But i have no idea how. I guess i maybe should use JOIN and num_rows()?

Please ask if you dont understand, so i can explain better.

Have a nice day!

$this->db->select('COUNT(*) as count, recensions.anme_id as recension_id')
->from('recensions')
->join('comments','recensions.anme_id = comments.anme_id','left')
->group_by('anme_id');
$result = $this->db->get();

Should give you the recensions id and the comment count for that id.

then loop:

foreach($result->result() as $row){
    echo "Recension id $row->recension_id has $row->count comments<br />";
}

I don't know about the database connector you are using, but in pure SQL (assuming the connection recensions.id=comments.anme_id connection), try this:

SELECT COUNT(comments.id), anme_id
FROM recensions
LEFT JOIN comments on comments.anme_id=recensions.id
GROUP BY anme_id

Like this??

$sql = mysql_query("SELECT * FROM recensions");
while($row = mysql_fetch_array($sql)){
$amne_id = $row{"amne_id"};
$sql2 = mysql_query("SELECT * FROM comments WHERE amne_id='$amne_id'");
$total_comments = mysql_num_rows($sql2);
echo $total_comments;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM