gpt4 book ai didi

MYSQL:复杂的查询,多个 JOIN-s?

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:06 26 4
gpt4 key购买 nike

有可以更改的数据库结构(比方说遗留数据库),我需要对其实现额外的请求。

数据库结构:

Table "content" (few million rows)
=============================================
║ user_id ║ item_id ║ prop1 ║ prop2 ║ ... ║
=============================================

Table "descriptions" (less than 1 million rows)
========================
║ item_id ║ type ║ ... ║
========================

Table "properties" (multi million rows)
===================
║ prop_id ║ value ║
===================

我需要找到某个特定类型 (type) 的用户 (user_id) 拥有的所有项目,并计算相乘的 prop1 和 prop2 的总和。
IE。 ∑(prop1*prop2) 其中 user_id=... 和 type=...最终结果为一个整数值。

问题是数据被拆分到 3 个表中,我不知道如何加入它们。可能甚至不可能通过单个查询来实现它。

问题:从数据库性能的角度计算值的最佳方法是什么?拆分为几个更简单的查询或运行一些复杂的查询?

最佳答案

即使您的第一个表似乎没有规范化,您也应该能够加入正在考虑的两个属性。

select
c.user_id,
d.type,
sum( p1.value * p2.value ) as SumOfP1TimesP2
from
content c
JOIN descriptions d
on c.item_id = d.item_id
JOIN properties p1
on c.prop1 = p1.prop_id
JOIN properties p2
on c.prop2 = p2.prop_id
where
c.user_id = parmSomeUserIDKey
group by
c.user_id,
d.type

请注意属性表被使用了两次...每个别名引用对应于主内容表中每个单独的 prop1 和 prop2 字段。

如果要查找 SINGLE 类型,只需将其添加到 where 子句即可。

此外,如果您只关心单个数字,并且知道两个 ID(相对于类型的描述),您甚至可以通过以下方式进一步简化:

select
sum( p1.value * p2.value ) as SumOfP1TimesP2
from
content c
JOIN properties p1
on c.prop1 = p1.prop_id
JOIN properties p2
on c.prop2 = p2.prop_id
where
c.user_id = parmSomeUserIDKey
AND c.item_id = d.item_id

请注意,正如您对性能的评论。只要你有好的指标,你就应该是好的。我建议存在以下内容。

属性表,您可能已经拥有 (prop_id)但对于内容表——索引 (user_id, item_id)… 明确索引中的两个字段。由于您想要单个用户/项目,它应该非常快,除非单个用户/项目有几百万行(我怀疑)。即使一个人/项目有 10k 行要计算也应该非常快。

关于MYSQL:复杂的查询,多个 JOIN-s?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52524890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com