V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
dreamramon
V2EX  ›  问与答

请教一个关联查询的 sql

  •  
  •   dreamramon · 2023-02-26 21:02:39 +08:00 · 751 次点击
    这是一个创建于 425 天前的主题,其中的信息可能已经有所发展或是发生改变。

    数据库用的 postgres 14

    现在有 3 张表, app, appuser, x ,其中 appuser 为 app 和 user 的映射关系,一个 app 会有多个 user

    其中 app 的示例

    id name x_id
    1 1 1
    2 1 2

    appuser 示例

    id app_id user_id
    1 1 1
    2 1 2

    x 的示例

    id name
    1 xxx
    2 yyy

    现在业务需求是做一个 app 的页面,其中一个表格,每行显示对应的 app.id, app.name, userCount, x.id, x.name

    其中 x.idx.name 把 app 表和 x 表 join 起来查询就可以。。。但是请教高手,可以怎样一行 sql 把该 app 对应的用户数也 count 出来?

    6 条回复    2023-02-26 23:23:37 +08:00
    liprais
        1
    liprais  
       2023-02-26 21:09:50 +08:00
    理解一下 join 到底干了啥:
    把多行满足条件的数据拼接到一行里面
    现在你有这一行数据了,group by 不就完了
    pendulum
        2
    pendulum  
       2023-02-26 21:29:47 +08:00
    SELECT "a"."id", "a"."name", COUNT("b"."user_id") AS "userCount", "x"."id", "x"."name" FROM "app" AS "a"
    INNER JOIN "x" ON "a"."x_id" = "x"."id"
    INNER JOIN "appuser" AS "b" ON "a"."id" = "b"."app_id"
    GROUP BY "b"."app_id"
    dreamramon
        3
    dreamramon  
    OP
       2023-02-26 22:10:34 +08:00
    @pendulum #2
    老是要提示这个。。。
    > ERROR: column "app.id" must appear in the GROUP BY clause or be used in an aggregate function
    高手帮忙看看呗。。。是不是这个 group by 有什么讲究~~~
    mywind
        4
    mywind  
       2023-02-26 22:56:06 +08:00
    SELECT app.id, app.name, COUNT(appuser.id) as userCount, x.id, x.name
    FROM app
    JOIN x ON app.x_id = x.id
    LEFT JOIN appuser ON app.id = appuser.app_id
    GROUP BY app.id, x.id;
    试试这个
    awen233333
        5
    awen233333  
       2023-02-26 23:12:46 +08:00
    @dreamramon select 里没有使用聚合函数的列都要放在 group by 语句后面
    xiaoxixi
        6
    xiaoxixi  
       2023-02-26 23:23:37 +08:00
    SELECT
    app.id
    , app.name
    , COUNT(1) over(partition by appuser.app_id ) as userCount
    , x.id
    , x.name
    FROM app
    LEFT JOIN appuser ON app.id = appuser.app_id
    LEFT JOIN x ON app.x_id = x.id
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1875 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:38 · PVG 00:38 · LAX 09:38 · JFK 12:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.