我需要写一个这样的查询,请帮忙吗?
select id, parent, faq,
(select count(*) from faq_table where parent =
(select id from faq_questions) group by id)
as reply from faq_table
此表存储问题和答案(如常见问题解答),答案在父列中获取问题ID的值。理想情况下,我还想添加名为par的第二列,其中所有问题的值都为1.
像:
id | parent | faq
19 | 0 | name a president of the US
20 | 19 | Bush
21 | 19 | Obama
22 | 0 | Can Canada win the WC match against the Lankan's today
23 | 22 | Yes because Cheema is going to make a double today
在该查询的结果表中,我必须得到:
id | parent | faq | reply | par
19 | 0 | name a president of the US | 2 | 1
20 | 19 | Bush | 0 | 0
21 | 19 | Obama | 0 | 0
22 | 0 | Can Canada win the WC match against the Lankan's today | 1 | 1
23 | 22 | Yes because Cheema is going to make a double today | 0 | 0
答案 0 :(得分:2)
这仅适用于单个层次结构级别:
SELECT t.id, t.parent, t.faq, IFNULL(g.Cnt, 0) as reply,
g.Cnt IS NOT NULL AS par
FROM faq_table t LEFT JOIN (
SELECT parent, COUNT(*) Cnt
FROM faq_table
WHERE parent > 0
GROUP BY parent
) g ON t.id = g.parent
否则,您可以使用子查询:
SELECT t.id, t.parent, t.faq,
(SELECT COUNT(*) FROM faq_table f WHERE f.parent = t.id) as reply,
(SELECT COUNT(*) FROM faq_table f WHERE f.parent = t.id) > 0 As par
FROM faq_table t
答案 1 :(得分:1)
使用您的查询和此事实
要求
第二列名为par,其中所有问题的值都为1.
变得微不足道,似乎与您的数据一致。
select id, parent, faq,
(select count(*) from faq_table where parent =
(select id from faq_questions) group by id)
as reply,
if(parent=0,1,0) as par
from faq_table
基本上当parent = 0时,它是父级。但由于注释声明只有一个表,因此上面必须是伪 - 正确的查询应该是
select id, parent, faq,
(select count(*) from faq_table t where t.parent = faq_table.id) as reply,
case when parent = 0 then 1 else 0 end as par
from faq_table
答案 2 :(得分:1)
此版本也有效;
SELECT q.id, q.parent, q.faq, count(a.id) AS reply, IF(ISNULL(a.id),0,1) as par FROM faq_table q LEFT JOIN faq_table a ON q.id = a.parent AND a.id IS NOT NULL GROUP BY q.id
答案 3 :(得分:0)
试一试
SELECT
f.id,
f.parent,
f.faq,
(SELECT COUNT(*) FROM faq_table f2 WHERE f2.id = f.parent) AS reply
FROM faq f