一个有点棘手的mysql查询

时间:2012-04-16 17:53:18

标签: mysql sql

我在mysql db上有2个表

auctions:

seller: seller id
transaction_date: unix timestamp


comments:

seller: seller id
rating (-1, 0, 1)
comment_date: unix timestamp

所以,我想在交易之前计算卖家的卖家评级,即评级的总和。我想知道卖家在交易前有多少评论。

我想再获得两个这样的列:

拍卖:

卖家,交易, seller_rating,num_of_comments

任何想法? 提前谢谢。

2 个答案:

答案 0 :(得分:3)

以下内容可能有效。基本上,您构建一个表,列出每个事务的所有相关注释,然后从那里执行计数:

SELECT auctions.seller, auctions.transaction_date, SUM(comments.rating) AS seller_rating, COUNT(comments.comment_date) AS num_of_comments
  FROM auctions
  LEFT OUTER JOIN comments 
    ON auctions.seller = comments.seller
  WHERE auctions.transaction_date > comments.comment_date
GROUP BY auctions.seller, auctions.transaction_date

答案 1 :(得分:1)

这应该这样做:

SELECT
  a.seller,
  a.transaction_date,
  SUM(c.rating),
  COUNT(*)
FROM auctions a 
LEFT JOIN comments c on c.seller = a.seller AND c.comment_date <= a.transaction_date
GROUP BY a.seller