2015-04-05 90 views
1

此表存儲誰購買了哪本書以及何時購買的數據。我想知道哪些書是由USERID#1首先購買的。 SQL fiddleMysql select min in userid userid =?

這將導致

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 
+0

我不明白你想達到什麼。用'this'和'This'太寬泛,請指明你的需要。 – 2015-04-05 08:57:05

+0

如果用戶#1在用戶#2的同一天購買了該書,並且沒有人比他早購買該書,該怎麼辦? – eggyal 2015-04-05 09:00:25

回答

0

要篩選一group-wise minimum,這本身就是使用自聯接(爲了尋找第一次購買之日起制定只有那些期望的用戶買的,不管購買的書籍):

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 

看到它的sqlfiddle