开发者

Performing a multi-table inner/left/right join (or correlated subquery) with count?

I'm wondering how exactly to perform a 3-way join using the following structure (much simplified)

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

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

**Table 3**
owner.id

My goal here is very basically to count the number of votes that an 'owner' has. I keep thinking I can simply do this using a correlated subquery, but that seems like it would be a performance hog if votes is huge? Maybe i'm wrong? I just can't get my head around a 3 (or more) table like开发者_运维问答 this. Is it possible to do this in 1 query rather than 2 steps?

ie:

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

Would something like this even work? Is there a better, more efficient way to do this?

Any help or advice is very much appreciated as always


As simple as that:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜