【问题标题】:Performing a multi-table inner/left/right join (or correlated subquery) with count?使用计数执行多表内/左/右连接(或相关子查询)?
【发布时间】:2011-11-16 13:36:39
【问题描述】:

我想知道如何使用以下结构准确执行 3 路连接(非常简化)

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

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

**Table 3**
owner.id

我的目标基本上是计算“所有者”的投票数。我一直在想我可以简单地使用相关的子查询来做到这一点,但是如果选票很大,这似乎会影响性能?也许我错了?我只是无法在这样的 3 (或更多)表周围。是否可以在 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

这样的东西会起作用吗?有没有更好、更有效的方法来做到这一点?

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

【问题讨论】:

    标签: mysql sql database join business-logic


    【解决方案1】:

    就这么简单:

    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
    

    【讨论】:

    • 就这样?嗯。我认为这很容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    相关资源
    最近更新 更多