Question

I have a php web page and I got a problem with counting data using group by in mysql query

When any question submitted, id is automatically add and idqu=0 if question replied then idqu is equal to replied question's id

My table and data

id idqu question answer    user    date

1   0   quest1             test    28042014

2   0   quest2             scott   29042014

3   2   reply1             andy    01052014

4   0   quest3             test    01052014

5   4   reply2             scot    01052014

My question is how can I count question's reply?

quest1 (0)

quest2 (1)

quest3 (1)
Was it helpful?

Solution

This query does the job. I gave the table the name "tbl"

Select q.id, count(a.id) as answers

From tbl q

Left join tbl a on a.idqu=q.id

Where q.idqu=0

Group by q.id

OTHER TIPS

Try this

    Select t1.question, count(t2.id) as counts
    From table1 t1
    Left join table1 t2 on t2.idqu=t1.id
    Where t1.idqu=0
    Group by t1.id

DEMO

select idqu, count(idqu) as reply_count
from   table_name
where  idqu <> 0
group by idqu

This is for every replies, with a bit of php. You don't need group by I think.

$query="SELECT * From YourTable WHERE idqu>0";
$res=mysql_query($query);
mysql_num_rows($res);

If you want to select replies on one question, add an AND idqu=(yourInt) in the query.

Hope I did understand and replied correctly!

If I understand correctly, try:

SELECT question, SUM(CASE WHEN idqu > 0 THEN 1 ELSE 0 END)
FROM tablename
GROUP BY question
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top