0

そのようなデータを含むテーブルがあります。これは質問/回答スクリプトの例です。ID は自動インクリメントで、PID=0 の場合は質問で、質問に回答すると PID が質問の ID に設定されます。返信の件名はありません。

ID    PID    SUBJECT                CONTENT                   DATE
1      0     First Question         This is my first          09/01/2013
2      0     Second Question        This is second            09/01/2013
3      1                            Yes this is first         09/01/2013
4      2                            I agree this is second    10/01/2013
5      0     Third Question         This is third question    11/01/2013
6      1                            Reply to first            11/01/2013
7      1                            Another reply to first    12/01/2013
8      5                            This is reply of 5th      13/01/2013
9      2                            Last try for second       14/01/2013

私の質問は、

返信回数のある質問を選択するにはどうすればよいですか?

Ex.
First Question (3)
Second Question (2)
Third Question (1)

今日の回答済みの質問または回答を選択するにはどうすればよいですか?

Ex. For 09/01/2013
First Question (2) ---> 1 question and 1 answer but 2 actions
Second Question (1) ---> just 1 question
4

3 に答える 3

1

Select the questions and join against the answers:

select q.id, q.subject, count(a.id)
from yourtable q
left join yourtable a on q.id=a.pid
where q.pid=0
group by q.id;
于 2013-01-08T08:20:19.183 に答える
0

質問 1 の場合

select PID,count(*) from table
where pid<>0 
group by PID

質問 2 の場合

select PID,count(*) from table
where pid<>0 and date=current_date()
group by PID
于 2013-01-08T08:13:03.817 に答える
0

Try join for first task

SELECT 
    q.id as ID,
    q.pid as PID,
    q.subject as SUBJECT,
    COUNT(lq.id) as Total
FROM questions as q
LEFT JOIN questions as lq ON lq.pid = q.ID
WHERE q.PID = 0
GROUP BY q.id

OUTPUT

ID  PID     SUBJECT             TOTAL
1   0       First Question      3
2   0       Second Question     2
5   0       Third Question      1

Demo

EDITS :
For second part. You should note that there can be many other ways for doing the same task.

SELECT 
    q.id as ID,
    q.pid as PID,
    q.subject as SUBJECT,
    (COUNT(lq.id) - 1) as Total,
    q.date
FROM questions as q
LEFT JOIN questions as lq ON lq.pid = q.ID OR lq.id = q.PID
WHERE q.date = DATE(NOW())

OUTPUT

ID  PID     SUBJECT             TOTAL   DATE
1   0       First Question      2       January, 09 2012 00:00:00+0000
2   0       Second Question     1       January, 09 2012 00:00:00+0000

Demo

于 2013-01-08T08:26:14.897 に答える