简体   繁体   中英

SQL Queries for combining data

I would appreciate any help regarding the following challenge (for me). Really sorry for my novice question.

I have the following table ([USER ID] has borrowed the book entitled [Book Title] on [Timestamp]):

USER ID | Book Title | Timestamp
--------------------------------
   1    |   Alpha    | 10/10/2007
   2    |   Beta     | 12/02/2010
   3    |   Gama     | 03/05/2011

etc. What I would like is to make a list with the following type of rows:

UserID A | UserUD B | Book Title| Timestamp

If two [USER ID] have borrowed the same [Book Title], I would like to list them as above mentioned, but also keep the [Timestamp] of the latest borrowing.

Does anyone know how to write it in PHP?

Until now I have write the code for combining the users who have borrowed the same [Book Title] but I have not yet figured out how to attach the timestamp to this list.

I would appreciate any kind of help.

You can then do this with a join :

select ft.userid as userid1, ft2.userid as userid2,  ft.booktitle,
       ft2.timestamp
from followingtable ft join
     followintable ft2
     on ft.booktitle = ft2.booktitle and
        ft.timestamp < ft2.timestamp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM