【问题标题】:SUM acorrding to another column根据另一列求和
【发布时间】:2012-02-10 21:48:21
【问题描述】:

我需要知道是否有没有子查询的可能方法..

这是我的表结构:

id-name-father_id
1  joe    0
2  mark   0
3  muller 0
4  miki   2
5  timi   2
6  moses  2
7  david  1
8  momo   0
9  daniel 0
10 ermi   3

我的表逻辑是

  • 0 表示他不是某个人的孩子

  • 1+表示他是那一排的人子。

注意:如果有人有孩子,他仍然 父亲 ID 为 0(这意味着我的表中没有祖父)

我的查询是:

SELECT id, name, count(id=father_id) as sons
WHERE father_id = 0

我想要得到的是非儿童(father_id=0)sum 的列表 它有的孩子。 有没有办法在没有子查询的情况下获得结果?

【问题讨论】:

    标签: php sql select count sum


    【解决方案1】:

    应该这样做(MySQL):

    SELECT `parents`.`id`, `parents`.`name`, COUNT(`children`.*) AS sons
    FROM `people` AS parents
    LEFT JOIN `people` AS children ON `parents`.`id` = `children`.`father_id`
    WHERE `parents`.`father_id` = 0
    GROUP BY `parents`.`id`
    

    根据Gary的说法,我们需要在其他SQL数据库中将name添加到GROUP BY

    SELECT `parents`.`id`, `parents`.`name`, COUNT(`children`.*) AS sons
    FROM `people` AS parents
    LEFT JOIN `people` AS children ON `parents`.`id` = `children`.`father_id`
    WHERE `parents`.`father_id` = 0
    GROUP BY `parents`.`id`, `parents`.`name`
    

    我们在这里加入了自己的桌子。所以我们和所有的父母和他们的孩子一起。

    这将导致这样的结果:

    parents.id  parents.name children.id  children.name
    1           joe          7            david
    2           mark         4            miki
    2           mark         5            timi
    2           mark         6            moses
    3           muller       10           ermi
    8           momo         -            - # left join allows this line
    9           daniel       -            -
    

    但现在我们每个父母都有几次。所以我们在父 ID 上对整个事情进行 GROUP'ing,这将导致以下结果:

    parents.id  parents.name COUNT(children.*)
    1           joe          1
    2           mark         3
    3           muller       1
    8           momo         0
    9           daniel       0
    

    【讨论】:

    • 我认为您还需要将 parents.name 添加到 group by 子句中
    • 哎呀,误解了你(赞成票是为了提醒我 SELECT 中的name 是模棱两可的,我需要parents.name);)为什么我需要组中的名称? ID 已经是唯一的了,不是吗?名字不会有什么不同。也许我问错了?
    • +1 值得一提的是,尽管可以在任何 SQL 中使用相同的通用方法,但此查询的某些功能是 MySQL 特定的(即select 子句中的反引号名称和未聚合的未分组列分组查询)。
    • 我对 MySQL 不是 100% 确定,但我使用过的其他 SQL 数据库(Postgres、Oracle、MSSQL 是肯定的)将要求输出中包含的任何列不经过聚合函数在 GROUP BY 子句中提到。即使 GROUP BY 子句已经有唯一键。
    • 好的,那我就加进去。我只知道MySQL。感谢您的评论:)
    【解决方案2】:

    您应该能够在没有任何连接或子查询的情况下执行此操作,如下所示:

    select case father_id when 0 then id else father_id end id,
           max(case father_id when 0 then name end)     name,
           sum(sign(father_id))                         sons
    from table
    group by case father_id when 0 then id else father_id
    

    【讨论】:

    • 我不熟悉“case x when y then z”,但它对性能问题有好处吗...
    • 性能并不是 - 在关系数据库中,通常是对表的逻辑访问会真正降低性能。在这里,表只被访问一次——理论上,它应该比任何多次访问同一个表的查询都要快,尽管在实践中(特别是如果表很小)这种差异可能并不显着。
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多