mysql 10万级join,mysql:如何INNER JOIN表,但限制联接到具有最高投票或计数的1结果?...

I have 2 tables. One is items and another is votes for those items.

Items table has: |item_id|name|post_date

Votes table has: |votes_id|item_id|answer|total_yes|total_no

What I want to do is show all items based on post_date and show the answer in the votes table with the HIGHEST total_yes. So I want to show only a SINGLE answer from the votes table with the highest total_yes vote.

I was trying:

SELECT a.*, b.* FROM Items a

INNER JOIN Votes b ON a.item_id = b.item_id

GROUP by a.item_id

ORDER by a.post_date DESC, b.total_yes DESC

But that doesnt work.

The result I would like to see is:

Buick | Fastest | 2 yes votes

Mercedes | Shiny | 32 yes votes

Honda | Quick | 39 yes votes

Any help is appreciated!

解决方案SELECT a.*, b.*

FROM Items a

LEFT JOIN Votes b on a.item_id = b.item_id

and b.total_yes = (select max(total_yes)

from Votes v

where v.item_id = a.item_id)

ORDER BY a.post_date DESC, b.total_yes DESC

N.B.: if you have for an item 2 answers with the same total_yes = max, you will have 2 rows for that item.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值