我有一張items桌子
| ID | 姓名 |
|---|---|
| 1 | 納努 |
| 2 | 凱 |
| 3 | 洛 |
我還有一張item_usages桌子:
| ID | item_id | 用戶身份 | 使用時間 | |
|---|---|---|---|---|
| 1 | 1 | 99 | 2021-10-07 00:00:00 | |
| 2 | 2 | 99 | 2021-10-07 00:00:00 | |
| 3 | 1 | 99 | 2021-10-08 00:00:00 | |
| 4 | 1 | 22 | 2021-10-08 00:00:00 | |
| 5 | 3 | 22 | 2021-10-08 00:00:00 | |
| 6 | 1 | 99 | 2021-10-08 00:00:00 |
我想在查詢中查找專案的總使用量和用戶使用量。一個例子我想找到 user_id 99 的用法,預期結果:
| ID | 姓名 | 總用量 | 用戶使用 |
|---|---|---|---|
| 2 | 凱 | 1 | 1 |
| 1 | 納努 | 4 | 3 |
| 3 | 洛 | 1 | 0 |
我試過:
select
"items".*,
count(total_usage.id) as total_usage,
count(user_usage.id) as user_usage
from
"items"
left join
"item_usages" as "total_usage" on "items"."id" = "total_usage"."item_id"
left join
"item_usages" as "user_usage" on "user_usage"."item_id" = "items"."id"
and "user_usage"."user_id" = 99
group by
"items"."id";
但它回傳:
| ID | 姓名 | 總用量 | 用戶使用 |
|---|---|---|---|
| 2 | 凱 | 1 | 1 |
| 1 | 納努 | 12 | 12 |
| 3 | 洛 | 1 | 0 |
item_usages只有 6 行,為什么 Nganu 在兩種用法上都有 12 行?如何解決我的查詢?
我在 PostgreSQL 12.8 和 13.4 上嘗試過,我也在 SQLFiddle(PostgreSQL 9.6) 上測驗過,這是鏈接:
http://sqlfiddle.com/#!17/f1aac/5
我得到了回傳正確結果的查詢:
select
"items".*,
min(total_usage.total_count) as total_usage,
count(user_usage.id) as user_usage
from "items"
left join
(select item_id,count(item_id) as total_count from item_usages group by item_id) as total_usage
on "items"."id" = "total_usage"."item_id"
left join "item_usages" as "user_usage"
on "user_usage"."item_id" = "items"."id" and "user_usage"."user_id" = 99
group by "items"."id";
但是我不知道性能,所以如果可能的話我仍然會找到更快的查詢并且仍然想知道:
為什么我的第一個查詢給出錯誤的結果?
uj5u.com熱心網友回復:
您的查詢回傳高數字的原因是您加入了 2 次。
(從 Nganu 的一側)第一個連接將產生 4 行,第二個將這 4 行映射到同一個表的 3 行,從而產生 12 行。
你可以只用 1 個連接來解決這個問題:
select "items".id,
count(total_usage.id) as total_usage,
sum(case when total_usage.user_id = 99 then 1 else 0 end) as user_usage
from "items"
left join "item_usages" as "total_usage" on "items"."id" = "total_usage"."item_id"
group by "items".id
它應該作業得更快(雖然,在一個小資料集上是不可見的)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315224.html
標籤:sql PostgreSQL 加入 数数 左连接
