How is a gallery associated with some post in database?

WordPress galleries are implemented as shortcodes: the shortcode should appear in the post_content of your “basic” post (whose post_type="post"). The shortcode’s parameters specify the images to be included in the gallery by giving the post ID of the attachment-type post containing each image. So if you see two posts in wp_posts like this:

id | post_title                   | post_type  | post_parent
 1 | This post contains a gallery | post       | 0
 2 | IMG_0954                     | attachment | 1

If the first post contains the second in a gallery, its post_content will contain something like this:

You’ll notice that the attachment post’s post_parent is set to the ID of the post containing it, but this doesn’t necessarily matter to the gallery: it will include whatever attachment post IDs are given in the ids="" parameter to the shortcode.

So there is no direct database relationship between a post with a gallery and that gallery’s contents; it’s all determined by the shortcode present in the post’s content.

For a more thorough understanding of how the gallery gets generated, including the fact that you can override its output with your own using the post_gallery filter hook, see the source for the gallery_shortcode function in media.php