I don't know how WPs library is built, but it's Open source, you can take a look.
As for table structure, assuming you want a many-to-many link you'd want a cross reference table, something like:
record_id (int)
media_id (int)
title (text)
caption (text)
rank (int)
Then the media table would be something like:
id (int)
title (text)
caption (text)
filename (text)
type (image|multimedia|document)
Perhaps you'd also add a folder_id field to the media table, or perhaps you instead want tagging, in which case you have a third table with media_id and tag as fields (or you have tags as comma separated values in the media table).
This will let you link one media to multiple items and one item to multiple media. It'll let you set a title and caption for the media item and override it for a specific link. For instance you have a picture of a house with the caption of whose house it is, but in one link the caption is overwritten (in the cross reference table) with text saying how this house is an example of a certain architecture. SQL's coalesce function will come in handy for getting the correct title and caption.
If the content that links to media comes from multiple table, say you have a table called 'staff' and another called 'products' and they can both link to media, then the cross reference table also needs to have a *table_name* field. The type field is so that you can easily get only the multimedia attached to a record, or only the images; you may want to count how many documents are attached, how many images etc, basing this off the filename on each query means you have slower queries.
One thing this doesn't quite cater for is hosting the media off site. If you use say Amazon S3 for storing these images, then the 'filename' field would actually be a URL to the image. I'm just shooting this out there as something you need to take into consideration when designing the media library.
I can't think of any literature or code you can copy-paste though, it's not difficult to do, though I do appreciate this can be time consuming.
Best of luck.