【问题标题】:Is it possible to ORDER a parent table based on a CHILD table in SQL- PostgreSQL?是否可以根据 SQL-PostgreSQL 中的 CHILD 表对父表进行排序?
【发布时间】:2020-02-27 01:15:51
【问题描述】:

甚至可以通过子表对父表进行排序吗? 假设我有 person_ID(来自父表),该 person_ID 将在子表中获得很多选票。对于父表中的一个 person_id,子表中可以有这么多票。投票可以是 +1 或 -1。因此,如果 person_ID=001 获得 5 x(+1 票)和 2 x(-1 票)。 person_ID=001 的总分是+3。假设 person_ID=002 有 3 x (-1) 票。 Person_ID=002 的得分为 -3。 Person_ID=003 的得分为 0。

现在假设我想根据子表的总分对父表进行排序。

我知道如何对子表求和,但现在我需要根据子表的结果对父表进行排序。

  SELECT
  parent_id2,
  SUM (votes) AS total
  FROM childtbl GROUP BY parent_id2
  ORDER BY total DESC

我希望查询结果如下所示

Person_ID 001 | +3

Person_ID 003 | 0

Person_ID 002 | -3

这里是 SQL Fiddle 的链接。 http://www.sqlfiddle.com/#!17/ea694/6

这里是代码如果它搞砸了

CREATE TABLE parenttbl
(
    parent_id integer,
    test character(25),
    test2 character(25),
    PRIMARY KEY (parent_id)
);

INSERT INTO parenttbl (parent_id, test, test2) VALUES (1,'adam','test'), (2,'steven','test'), (3, 'bob','test');

CREATE TABLE childtbl
(
    child_id integer,
    parent_id2 integer,
    votes integer,
   PRIMARY KEY (child_id),
   FOREIGN KEY (parent_id2)
       REFERENCES parenttbl (parent_id) MATCH SIMPLE
       ON UPDATE NO ACTION
       ON DELETE NO ACTION
);

INSERT INTO childtbl (child_id, parent_id2, votes) VALUES (1,1,1), (2,1,1), (3, 1, 1),(4,1,-1), (5,2,1), (6, 2, 1),(7,3,-1), (8,3,-1), (9, 3, -1),(10, 1, 1),(11,3,1),(12,3,1),(13,3,1)

谢谢你们!

【问题讨论】:

    标签: sql postgresql left-join sql-order-by hierarchical-data


    【解决方案1】:

    如果我没看错,你只需要left join,聚合,排序:

    SELECT p.parent_id, COALESCE(SUM(c.votes), 0) total_votes
    FROM parenttbl p
    LEFT JOIN childtbl c ON c.parent_id2 = p.parent_id
    GROUP BY p.parent_id
    ORDER BY total_votes DESC
    

    left join 允许父母没有投票权,在这种情况下,COALESCE(SUM(c.votes), 0) 给出0

    您可能还想预先聚合子表,因此您不需要在外部查询中进行聚合 - 这使得从父表返回更多列看起来很简单(而在前一个查询中,您需要将每一列添加到group by 子句):

    SELECT p.*, COALESCE(c.votes, 0) total_votes
    FROM parenttbl p
    LEFT JOIN (
        SELECT parent_id2, SUM(votes) votes FROM childtbl GROUP BY parent_id2
    ) c ON c.parent_id2 = p.parent_id
    ORDER BY total_votes DESC
    

    【讨论】:

    • 感谢您的回复!感谢作品!还有一种方法可以让分数在查询中也显示出来,比如 c.votes 的总和?
    • 病夫!棒极了。这是一个复杂的查询还是对你来说很容易?我只是在学习。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2010-10-15
    • 2023-03-07
    • 2019-09-26
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    相关资源
    最近更新 更多