包括具有零计数()值的行

时间:2014-01-27 07:52:00

标签: mysql graph count relational-database relation

我正在设计一个基于标签的伪类别系统。

我有两个表 - 连接和关键字。 'keyword'定义了类别,'connection'是邻接列表。

单击某个类别时,视图会显示子类别。

SELECT kw.kw_id, kw.kw_name, kw.kw_desc
FROM keyword AS kw, connection AS conn
WHERE conn.kw1id = :kw1 AND conn.kw2id = kw.kw_id

这很好用,但现在我想根据孩子的数量对这些子类别进行排序。

SELECT  child.id AS child_id, keyword.kw_name AS child_name, keyword.kw_desc AS child_desc,
            COUNT(r1.conn_id) AS out_degree
FROM keyword
INNER JOIN connection AS r1 ON r1.kw1id = keyword.kw_id
INNER JOIN (
    SELECT kw2id AS id
    FROM connection AS conn
    WHERE conn.kw1id = [ID_CLICKED]
) AS child ON child.id = r1.kw1id

GROUP BY r1.kw1id

ORDER BY out_degree DESC

但这仅返回带有> 0个孩子的类别。如何包含叶节点?

2 个答案:

答案 0 :(得分:1)

只需将INNER替换为LEFT即可...

顺便说一下,你真的不需要那个子查询

很难确定,但从你的描述我认为这样的东西就是你想要的?

 SELECT  k.id AS child_id,   
         k.kw_name AS child_name,  
         k.kw_desc AS child_desc,
         COUNT(rb.conn_id) AS out_degree
 FROM connection AS ra 
 LEFT JOIN keyword As k ON ra.kw2id = k.id AND ra.reltype = 'blah'
 LEFT JOIN connection As rb ON rb.kw1id = k.id AND rb.reltype = 'blah'
 WHERE ra.kw1id = [ID_CLICKED]
 GROUP BY k.id 
 ORDER BY out_degree DESC

这应该计算[ID_CLICKED]子女的子女,并且仍应包括无子女

为避免重复计算,请更改此项:

COUNT(rb.conn_id) AS out_degree

COUNT(distinct rb.kw2id) AS out_degree

所以每个大孩子只被计算一次

答案 1 :(得分:0)

更接近原始查询 - 这有效吗? (注意3 更改

SELECT  child.id AS child_id, keyword.kw_name AS child_name, keyword.kw_desc AS child_desc,
            COUNT(r1.conn_id) AS out_degree
FROM keyword
**LEFT** JOIN connection AS r1 ON **r1.kw2id** = keyword.kw_id
**LEFT** JOIN (
    SELECT kw2id AS id
    FROM connection AS conn
    WHERE conn.kw1id = [ID_CLICKED]
) AS child ON child.id = r1.kw1id
GROUP BY r1.kw1id
ORDER BY out_degree DESC
是的,我知道,一个问题的两个答案......但它们的答案不同: - )