Mysql muliple与子查询在同一个表上计数

时间:2018-01-09 13:30:06

标签: mysql count

我想只在一个表上进行特殊查询。以下是该表的示例:

TABLE NAME "market"
id    |code   |parent_id
------------------------
1     |aaaa   |0
2     |bbbb   |1
3     |cccc   |1

我想查询使用 id parent_id 列出包含两个变量的所有行:

  • 子计数 parent_id = id
  • 的行数
  • 父子 count:拥有该行的父级的行数

以下是我的查询,第一个计数是工作(子计数),但第二个计数总是 1 而不是好值 2

SELECT
     m1.*,
     m2.child_count,
     m3.parent_child_count
FROM
    market AS m1
LEFT OUTER JOIN (
    SELECT parent_id,COUNT(id) AS child_count FROM market GROUP BY parent_id
) AS m2
ON m1.id = m2.parent_id

LEFT OUTER JOIN (
    SELECT id,COUNT(id) AS parent_child_count FROM market GROUP BY id
) AS m3
ON m1.parent_id = m3.id
ORDER BY code ASC;

此查询的结果是:

QUERY RESULT
id    |code   |parent_id   |child_count  |parent_child_count
------------------------------------------------------------
1     |aaaa   |0           |2            |NULL
2     |bbbb   |1           |NULL         |1
3     |cccc   |1           |NULL         |1

ID 2 3 parent_child_count 的值应为 2 (与 child_count <相同/ strong> id 1

知道这种查询是否可行?

谢谢

2 个答案:

答案 0 :(得分:1)

试试这个(sql fiddle):

SELECT
     m1.*,
     m2.count AS child_count,
     m3.count AS parent_child_count
FROM
    market AS m1
LEFT OUTER JOIN (
    SELECT parent_id, COUNT(id) AS count FROM market WHERE parent_id != 0 GROUP BY parent_id
) AS m2
ON m1.id = m2.parent_id
LEFT OUTER JOIN (
    SELECT parent_id, COUNT(id) AS count FROM market WHERE parent_id != 0 GROUP BY parent_id
) AS m3
ON m1.parent_id = m3.parent_id
ORDER BY code ASC;

所以基本上你需要两次相同的计数,但你需要把它放在两个不同的地方。也许这可以简化,因为m2m3是同一个表。

答案 1 :(得分:1)

版本较短,不确定是否有更高的性能。

SELECT
     m.*,
     count(distinct childs.id) as child_count,
     count(distinct siblings.id) as parent_child_count
FROM
    market m
LEFT JOIN market as childs ON m.id = childs.parent_id
LEFT JOIN market as siblings ON m.parent_id = siblings.parent_id AND m.parent_id != 0
GROUP BY m.id
ORDER BY m.code ASC;