请教一个关联查询的 sql

2023-02-26 21:02:39 +08:00
 dreamramon

数据库用的 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 出来?

760 次点击
所在节点    问与答
6 条回复
liprais
2023-02-26 21:09:50 +08:00
理解一下 join 到底干了啥:
把多行满足条件的数据拼接到一行里面
现在你有这一行数据了,group by 不就完了
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
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
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
2023-02-26 23:12:46 +08:00
@dreamramon select 里没有使用聚合函数的列都要放在 group by 语句后面
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/919334

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX