2013-01-08 119 views
0

我有一個表包含一些像這樣的數據。這是問題/答案腳本的示例。 ID是自動增量,如果PID = 0,那麼它是問題,當回答任何問題時,PID被設置爲問題的ID。沒有答覆的主題。Mysql從2行中選擇記錄

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 

回答

0

嘗試加入的第一個任務

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:
對於第二部分。你應該注意到可以有很多其他的方式來完成同樣的任務。

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()) 

輸出

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

+0

@Seyhan檢查編輯和演示!享受 –

+0

謝謝@raheel shan – Seyhan

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 
+0

這不正是我想要 – Seyhan

1

選擇問題,並加入對答案:

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; 
+0

感謝您的回覆,所以我怎麼能做到這一點對於今天的問題嗎? – Seyhan

+0

@Seyhan:添加'和q.date = curdate()'到where子句(假設你的日期列實際上是日期類型) – ysth