PHP: add Comments Count for each Post in array - php

I have 2 models "post_model" and "comment_model"
in Post_controller I get a result array from post_model which has all the posts.
I'm trying to add comments count for each post but I couldn't and need help.
comment table has post_id.
Please let me know how to handle this.
Thanks in advance.

Try this,
SELECT
p.post_id,
(SELECT count(c.post_id) FROM comments c WHERE c.post_id = p.post_id) cnt
FROM posts p
GROUP BY p.post_id LIMIT 5
Hope this will solve your problem.

Something like this should give you the number of comments for each post:
SELECT
COUNT(*) AS comment_cnt, post_id
FROM comment_table
GROUP BY post_id;
Then you can traverse the result set and enrich the corresponding post objects.
If you want to count comments only for some specific posts and you know their post_id, you could do something like:
SELECT
COUNT(*) AS comment_cnt, post_id
FROM comment_table
WHERE post_id IN (post_id1, post_id2, ...)
GROUP BY post_id;

SELECT p.post_id, p.post_title, p.post_content, p.user_id,count(c.post_id)
FROM posts p
LEFT JOIN comments c USING(post_id)
GROUP BY p.post_id, p.post_title, p.post_content, p.user_id;

Related

how to order data in mysql by join count?

I have two tables :
posts : id,title,content,show,created_at
comments: id,post_id,created_at
I'm trying to order posts by most commented.
SELECT *, COUNT(comments.id) AS total_comments
FROM comments LEFT JOIN posts ON posts.id = comments.post_id
WHERE posts.show = '1'
GROUP BY complains.id
ORDER BY total_comments DESC
The problem is that the posts with 0 comments don't appear.
Any help would be much appreciated.
With your join above, you are incorrectly joining to get commens that have posts
You should have done a right join or swap the tables in left join like below.
Select *, COUNT(comments.id) as total_comments
FROM posts
LEFT outer JOIN comments on posts.id = comments.post_id
WHERE posts.show = '1'
GROUP BY posts.id
ORDER BY total_comments DESC
You need to do a RIGHT JOIN instead of a LEFT JOIN. Or swap the tables in the LEFT JOIN clause.
While there are many ways to solve this, I think this code is easy to read and understand.
The query in the LEFT JOIN can be copied out and run on its own to help debug. Then you join that result set to the posts table and order the results.
SELECT p.*, IFNULL(c.total_comments, 0) as total_comments
FROM posts p
LEFT JOIN (select post_id, count(post_id) as total_comments from comments group by post_id) as c ON p.id = c.post_id
WHERE p.show = '1'
ORDER BY c.total_comments DESC

List comments by number of likes

I'm trying to get PHP to list out comments by descending number of likes they receive.
Currently, the comments' content and the number of likes they receive are in 2 separate tables: "comments" and "likes".
PHP code:
To get comments from "comments" table:
$this->db->order_by ('comment_id', 'asc');
$data['comment'] = $this->db->select()->get('comment');
To get likes from "likes" table:
$data['like'] = $this->db->get('like');
To show the number of likes for each comment:
$query_like=$this->db->query("select ip from like where comment_id='$comment_id'");
$count_like=$query_like->num_rows();
I'm wondering if it's possible to order the comments by the number of likes they receive without changing the tables' structure. Any advice hugely appreciated.
If I understand the data structure correctly, you just need a join and an aggregation:
select c.*, count(*) as numlikes
from comments c join
upvote l
on c.comment_id = l.comment_id
group by c.comment_id
order by count(*) desc;
EDIT:
To get comments with zero upvotes, do the left outer join in the other direction:
SELECT c.*, count(u.comment_id) as num_upvotes
FROM comment c left join
upvote u
on c.comment_id = u.comment_id
WHERE c.comment_id = '$interview_id'
GROUP BY c.comment_id
ORDER BY num_upvotes DESC;

joining a count on a query

I have 2 tables: comments & blog
blog has the following fields: id(Unique key),title, author, body, date, img, imgdes, tags
comments : key(Unique key), postid(related to the id of blog),name, email, date, message
Im trying to display all of my blog post and the number of comments on every post.
So im trying to "count(postid) where postid=id"
I got something to work but its based around having 1 comment which wont work but this is it:
SELECT a.postid,c.author,c.title, c.id,c.body,c.date,c.pic, c.tags, c.imgdesc,
COUNT(*) AS num_comments FROM comments a LEFT JOIN blog c ON c.id = a.postid
GROUP BY c.id order by id DESC"
Again this only work when everything has a comment and i get why but i cant figure out how to implement what I want.
To put it all out there i have:
$sql="***( help 1 of 2) what to set the query to****"
$query = mysql_query($sql) or die(mysql_error());
<?php do{ ?>
<html stuff here>
<?php echo $blog['title']?><br>
<?php echo $blog['*******(help 2 of 2) # of comments display here******']
<?php } while($blog = mysql_fetch_assoc($sql));?>
im sure this is a easy join but i have no clue thanks!
Use this query it may works for you
SELECT a.postid,c.author,c.title, c.id,c.body,c.date,c.pic, c.tags, c.imgdesc, COUNT(a.key) AS num_comments FROM blog c left outer join comments a ON a.postid = c.id GROUP BY c.id order by id DESC
if you want all the blog posts then it should be on the left side of the left join.
I think the issue lies where you write: FROM comments a LEFT JOIN blog c ON c.id = a.postid
GROUP BY c.id order by id DESC"
The comments a and blog c don't seem to be correct references.
Should it be FROM comments.a LEFT JOIN blog.c ON ...?
Are you trying to count the number of comments in each blog? if yes then,
SELECT c.postid,count(key) as num_of_comments
FROM blog b, comments c
WHERE b.id = c.postid
GROUP BY c.postid
Another easy way out:
As you have the postid as a foreign key, you can just get the results from comments table
SELECT postid,count(key) as num_of_comments
FROM comments
GROUP BY postid

php query with 2 counts and joins

im running a query that usses 3 tabels "post, likes and comment" i need to get the ammount of likes and comments the post has got, and at the same time get the basic info from the post table so im using the query bellow but the problem is that it copys the value likeAmount to commentAmount if likes is bigger unless comments is 0.
SELECT post.*, COUNT(likes.id) as 'LikeAmount', COUNT(comment.id) as 'commentAmount' FROM post
LEFT JOIN likes ON post.id = likes.post
LEFT JOIN comment ON post.id = comment.post
GROUP BY post.id
ORDER BY LikeAmount DESC"
so that doesnt work but when i add distinct it does work, so when its like this:.
SELECT post.*, COUNT(distinct likes.id) as 'LikeAmount', COUNT(distinct comment.id) as 'commentAmount' FROM post
LEFT JOIN likes ON post.id = likes.post
LEFT JOIN comment ON post.id = comment.post
GROUP BY post.id
ORDER BY LikeAmount DESC";
i dont see why it works with distinct and doesnt with out, and does distinct mather performance wise or does it make no diffrence sinds it will be used in a website that has a lott of trafic..
try this, not short, but readable:
SELECT
p.*,
pl.like_count,
pc.comment_count
FROM post p
#join likes
LEFT OUTER JOIN (
SELECT
post,
COUNT(*) AS like_count
FROM likes
GROUP BY post
) AS pl
ON pl.post = p.id
#join comments
LEFT OUTER JOIN (
SELECT
post,
COUNT(*) AS comment_count
FROM comment
GROUP BY post
) AS pc
ON pc.post = p.id
Perhaps using SUM instead of COUNT to handle the records where there is no join would work, and should perform just as fast:
SELECT post.id,
SUM(IF(likes.id IS NULL,0,1)) as 'LikeAmount',
SUM(IF(comment.id IS NULL,0,1)) as 'commentAmount'
FROM post
LEFT JOIN likes ON post.id = likes.post
LEFT JOIN comment ON post.id = comment.post
GROUP BY post.id
ORDER BY LikeAmount DESC"

PHP & Mysql - Left Outer Join between two tables

I have two tables called 'events' and 'topics' each table can have many comments.
What I need to do is list all the events and topics with the amount of comments for each row. I've managed to return all the topics, which works great but I don't know how I can add the events table to the MySql. The comments and events table fields are listed below. Can anyone help me with this query?
Events:
ID
Event_Name
Comments:
post_id <-- the releated id for either the events or topics table
table <-- The table that the row belongs to so either topics or events
SELECT
t.id, t.title, c.created_at,
IF(ISNULL(c.allComments), 0, c.allComments) AS totalComments
FROM topics AS t
LEFT OUTER JOIN (
SELECT created_at, post_id, COUNT(*) AS allComments
FROM comments
GROUP BY post_id
) AS c ON c.post_id = t.id
ORDER BY tc.created_at DESC, c.allComments DESC
Sounds like events and topics should be the same table.
Still, I think we can do this with a UNION. Events and Topics have the same columns i hope? (Or at least the same important ones?)
(SELECT c.table as event_or_topic, e.*, count(C.table), MAX(C.created_at) as latest_c
FROM events E LEFT JOIN comments C on (C.post_id = E.id)
WHERE C.table = 'Events'
GROUP BY C.post_id)
UNION
(SELECT c.table as event_or_topic, t.id*, count(C.table), MAX(C.created_at) as latest_c
FROM topics T LEFT JOIN comments C on (C.post_id = E.id)
WHERE C.table = 'Topics'
GROUP BY C.post_id)
ORDER BY latest_c
Notice that the ORDER BY applies to the whole UNION, not the individual SELECTs.
The use of LEFT JOIN should allow those rows without Comments to still show. I think the problem is that we have parts of our select dependent on comments (ie - C.table, ordering on last comment, etc). The count should be fine - will just be zero if there are no comments.
You might need to change the SELECT part slightly. I'd like to display C.table so you know whether a row is a topic or event, but im afraid it might screw up the count. Do you need anything from comments besides the count? You use some columns other than post_id and table in your query that you neglected to explain in your question.
You still have columns I don't know what they are, like Comment's zoneTable
Try this:
SELECT
t.id, t.title, c.created_at, COUNT(c.allComments) AS totalComments
FROM topics AS t LEFT JOIN comments c ON t.id=c.post_id
GROUP BY t.id ORDER BY tc.created_at DESC, c.allComments DESC
If I understand your question you have 3 tables:
-Events
-Topics
-Comments
If that is true something like this should extract all the data:
SELECT *
FROM events,topics
LEFT JOIN comments ON post_ID = ID
ORDER BY date DESC
Hope i'm along the right lines!
W.
I've got it working. If anyone knows of a better and an efficient way of doing this, then please let me know:
(SELECT t.id, t.title, tc.dateCreated AS commentDate,
IF(ISNULL(tc.allComments), 0, tc.allComments) AS totalComments,
t.LastActive as dateChanged
FROM Events AS t
LEFT OUTER JOIN (
SELECT MAX(created_at) AS dateCreated, post_id,
COUNT(*) AS allComments
FROM comments
GROUP BY post_id
) AS tc ON tc.post_id = t.id)
UNION
(SELECT t.id, t.title, tc.dateCreated AS commentDate,
IF(ISNULL(tc.allComments), 0, tc.allComments) AS totalComments,
t.LastActive as dateChanged
FROM topics AS t
LEFT OUTER JOIN (
SELECT MAX(created_at) AS dateCreated, post_id,
COUNT(*) AS allComments
FROM comments
GROUP BY post_id
) AS tc ON tc.post_id = t.id)
ORDER BY commentDate DESC, dateChanged DESC, totalComments DESC

Categories