gpt4 book ai didi

mysql - 使用计数执行多表内/左/右连接(或相关子查询)?

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:44 24 4
gpt4 key购买 nike

我想知道如何使用以下结构(大大简化)执行三向连接

**Table 1:**
vote.id
vote.item_id

**Table 2:**
item.id
item.owner_id

**Table 3**
owner.id

我的目标基本上是计算“所有者”拥有的票数。我一直在想我可以简单地使用相关子查询来做到这一点,但如果投票很大,这似乎会是一个性能问题?也许我错了?我就是无法理解像这样的 3(或更多) table 。是否可以在 1 个查询而不是 2 个步骤中完成此操作?

即:

SELECT owner.id, 
(SELECT count(SELECT count(vote.id) as Cnt WHERE vote.item_id = item.id) as ItemCnt
WHERE item.owner_id = owner.id) as TotalCnt
WHERE owner.id = :id

这样的东西能行吗?有没有更好、更有效的方法来做到这一点?

一如既往地感谢任何帮助或建议

最佳答案

就这么简单:

select count(vote.id)
from owner
left join item on (item.owner_id = owner.id)
left join vote on (vote.item_id = item.id)
where owner.id = :id

关于mysql - 使用计数执行多表内/左/右连接(或相关子查询)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7409057/

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