【问题标题】:Select messages, calculate the votes average and know if an user already have voted it选择消息,计算平均票数并知道用户是否已经投票
【发布时间】:2013-07-21 14:49:56
【问题描述】:

我有一张表格,其中包含有关网站各种消息的投票信息。 该表称为votations,由以下组成:ID、messageID、userID、vote

我想从“messages”表中检索所有数据,计算“votations”表中的平均投票,并知道指定用户(将 userID 检查到“votations”表中)是否已经投票。这是检索消息和相应投票平均值的查询

select m.*, AVG(votes) as average_valuation from messages m 
left join votations v on v.messageID = m.id 
group by m.id

假设我收到的 userID 有 POST 数据,查询应该告诉我他是否已经在 LEFT JOIN 过程中投票了一条消息。我该怎么做?

【问题讨论】:

  • (messageID,userID) 的每个组合都是唯一的吗?如果是这样,为什么不是PRIMARY?
  • 是的,它是独一无二的......我应该设置为主要吗?
  • 好吧,这取决于你 - 但在我看来,在这种情况下你的代理键是多余的。
  • 在什么意义上?它不应该记住双重的 messageID+userID,因为一个用户至少可以对一条消息投票一次
  • 你的意思是说ID字段可能没用吗?

标签: mysql database


【解决方案1】:

尝试子查询

select 

m.*,
(
select count(1) from messages m1
where m1.id=m.id
and m1.userid=@userid
) as VotedAlready,

AVG(votes)
as average_valuation from messages m 
group by m.id

类似..

您还可以添加其他查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多