Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL count replies

I feel stupid for asking, but I have a small problem with my SQL.

Lets say, you have a Table with the following columns:

id (= The id of the post)
replyto (= The id of the post this post replies to)
replies (= The count of replies)

What I want to do, make a SQL query, that counts how many replies a post has and stores it in replies.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The Problem I’m having is that the id of the post and the reply count are in the same table, if it were different tables it would work, like how I count the like count.

UPDATE posts
SET likes = (SELECT COUNT(likes.id) FROM likes WHERE postid = posts.id)

But because I store replies as a post that have a set replyto value and a store in the same table, the above code does not work.

>Solution :

Table alias (the AS statement) allows you to refer to a table by an alias you give it, thus enabling you to compare values between same table.

Wrong answer:

UPDATE posts AS table1
SET replies = (SELECT COUNT(1) FROM posts AS table2 WHERE table2.replyto = table1.id)

Correct answer: (with caveats)

It seems you can’t use update on same table you are selecting from. The workaround is to wrap the offending query inside another.

UPDATE posts AS table1
SET replies = (select counter from (SELECT COUNT(*) AS counter FROM posts AS table2 WHERE table2.replyto = table1.id) as table3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading