我在postgres数据库中有多个表,它们包含完全独特的信息。当在查询中正确连接在一起时,信息将产生我正在寻找的所有可能的组合。我正在寻找的信息是完整的SKU。
要生成完整的SKU,此查询会生成所需的结果: 功能查询
SELECT
materials.code,
"part_base_parts".code as part_base_parts_id,
shanks.code AS shank_id,
measurements.description
FROM
"part_base_parts"
LEFT JOIN "part_types" ON "part_base_parts"."part_type_id" = "part_types"."id"
RIGHT JOIN "parts_to_shanks" ON "part_base_parts"."id" = "parts_to_shanks"."part_base_part_id"
RIGHT JOIN "parts_to_measurements" ON "part_base_parts"."id" = "parts_to_measurements"."part_base_part_id"
RIGHT JOIN "parts_to_materials" ON "part_base_parts"."id" = "parts_to_materials"."part_base_part_id"
JOIN materials ON "parts_to_materials"."material_id" = materials."id"
JOIN shanks ON "parts_to_shanks"."shank_id" = shanks."id"
JOIN measurements ON "parts_to_measurements"."measurement_id" = measurements."id"
ORDER BY
part_base_parts_id ASC,
materials.code ASC,
shank_id ASC,
measurements.description ASC
鉴于此查询,我生成了32,640条记录(未应用索引),查询时间为0.82秒。像这样......
给定输出
code part_base_parts_id shank_id description
AA 5105 A 03.0
.
. 32,638 rows in here.
.
ST 6939 D 9/16
但是,这只会让我走到一半。我需要从查询中取回结果并生成每列的计数总数。所以我需要的结果是:
期望的结果
code: AA - ###0
...
ST - ###0
part_base_parts_id: 5105 - ###0
...
6939 - ###0
shank_id: A - ###0
...
D - ###0
description: 03.0 - ###0
...
9/16 - ###0
有没有办法从Postgres产生“期望的结果”?
答案 0 :(得分:2)
如果你想要它们的行,那么肯定。
WITH cte AS(
SELECT
materials.code,
"part_base_parts".code as part_base_parts_id,
shanks.code AS shank_id,
measurements.description
FROM
"part_base_parts"
LEFT JOIN "part_types" ON "part_base_parts"."part_type_id" = "part_types"."id"
RIGHT JOIN "parts_to_shanks" ON "part_base_parts"."id" = "parts_to_shanks"."part_base_part_id"
RIGHT JOIN "parts_to_measurements" ON "part_base_parts"."id" = "parts_to_measurements"."part_base_part_id"
RIGHT JOIN "parts_to_materials" ON "part_base_parts"."id" = "parts_to_materials"."part_base_part_id"
JOIN materials ON "parts_to_materials"."material_id" = materials."id"
JOIN shanks ON "parts_to_shanks"."shank_id" = shanks."id"
JOIN measurements ON "parts_to_measurements"."measurement_id" = measurements."id"
ORDER BY
part_base_parts_id ASC,
materials.code ASC,
shank_id ASC,
measurements.description ASC
)
SELECT key, value, count(*)
FROM(
SELECT 'code' AS key, code AS value
FROM cte
UNION ALL
SELECT 'part_base_parts_id', code
FROM cte
UNION ALL
SELECT 'shank_id', shank_id
FROM cte
UNION ALL
SELECT 'description', description
FROM cte
) AS q
GROUP BY key, value
ORDER BY key, value