質問

I'm building a commenting system with PHP/MySQL. This commenting system has a nice feature, which allows users to highlight text (stored as "selected_text" in the database) and that highlighted text will then be stored in the database with the comment the user made. Additionally, I am also storing the paragraph (of which the highlighted text appeared), as an INT. These values are all storing properly in the database, but now I want to do something with them.

I want to create "comment counters." These comment counters will be placed next to each paragraph in the article, and they will display the total number of comments that were made on that paragraph to which they are attached. The visual overview of the "comments": table structure:

This is a view of the table structure

My latest query to attempt to retrieve this information is:

$distinct = mysql_query("SELECT COUNT(DISTINCT paragraph_id) FROM comments");

And the corresponding PHP code:

while ($result_three = mysql_fetch_array($distinct)) 
{ 
    echo $result_three['paragraph_id'];
}

Now, I think I may be going about this the wrong way. I have considered attempting to run a query that first finds all of the DISTINCT paragraph_ids. Following that, I would run a for each loop that counts the number of times those paragraph_ids appear.

The query I am working with right now does not seem to achieve my goal. Also, I am worried that there isn't a clear way for me to distinctly attach the counted data to a "comment counter."

役に立ちましたか?

解決

Basically, you need to count the comments in each group of paragraph ids. The correct query is below:

$distinct = mysql_query("SELECT paragraph_id, (DISTINCT comment_id) as comment_count FROM comments GROUP BY paragraph_id");

while ($result_three = mysql_fetch_array($distinct)) 
{ 
    echo $result_three['paragraph_id']; // Gives the id of the paragraph
    echo $result_three['comment_count']; // Gives the comment count for the associated paragraph
}

他のヒント

If I understand your problem correctly, you need to GROUP BY paragraph_id. Try this:

SELECT paragraph_id, COUNT(*)
FROM comments
GROUP BY paragraph_id

Its likely that you want to also know when there are zero comments you'll need to do an outer join to paragraphs.

SELECT p.paragraph_id,
       COUNT(c.comment_id) as comment_count 
FROM   comments c 
       RIGHT JOIN paragraphs p 
         ON c.paragraph_id = p.paragraph_id 
GROUP  BY p.paragraph_id 

here's a working data.se sample

Use below code, this should work

$res = mysql_query("SELECT COUNT(DISTINCT paragraph_id) as cnt FROM comments");

while ($result_three = mysql_fetch_assoc($res)) { echo $result_three['cnt']; }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top