mysql在userid =?的行组中选择min?

时间:2015-04-05 08:55:10

标签: mysql greatest-n-per-group

此表存储谁购买了哪本书以及何时购买的数据。我想知道USERID#1首先购买了哪些书籍。 SQL fiddle

这会导致

USERID  BOOKID  DATE_PURCHASE
1       2       2014-03-22 (purchased only by USERID #1)
1       5       2014-03-29 (purchased earlier than USERID #2)
1       6       2014-03-28 (purchased earlier than USERID #3)
1       7       2014-03-26 (purchased earlier than USERID #3)

它没有显示BOOKID#3,因为该书是由USERID#2首先购买的。

请注意,该表可能包含数万行,因此我需要一个有效的解决方案。

如果必须手动完成,我会这样做:

1. Check what books did USERID #1 buy
2. Go through all rows with those books (BOOKID) and check the MIN(DATE_PURCHASE) for each row
3. Write out those rows only where the USERID = #1

1 个答案:

答案 0 :(得分:0)

您想要过滤group-wise minimumsqlfiddle本身是使用自我加入制定的(为了找到首次购买所需用户购买的书籍的日期,无论购买者如何):

SELECT * FROM docs NATURAL JOIN (
  SELECT   BOOKID, MIN(d2.DATE_PURCHASE) DATE_PURCHASE
  FROM     docs d1 JOIN docs d2 USING (BOOKID)
  WHERE    d1.USERID = 1
  GROUP BY BOOKID
) t WHERE USERID = 1

在{{3}}上查看。