简体   繁体   English

如何在多个表上设置外键/查询

[英]How to setup foreign keys/queries on multiple tables

I'm trying to setup a database for a blog, it has the following tables: 我正在尝试为博客建立数据库,它具有下表:

posts (
   id,
   author_id,
   category_id,
)
authors (
   id,
)
categories (
   id,
)
tags (
  id
)
comments (
 id
)
comments_to_posts (
  comment_id,
  post_id,
)
tags_to_posts (
  tag_id,
  post_id,
)

The basic idea is this: 基本思想是这样的:

 many-to-1 tags-to-posts / 1-to-many posts-to-tags
 1-to-many authors-to-posts / 1-to-1 posts-to-authors
 1-to-many categories-to-posts / 1-to-1 posts-to-categories
 1-to-1 comments-to-posts / 1-to-many posts-to-comments
  1. I'm not sure which tables I should be putting the foreign keys on etc... I've been experimenting trying different combinations but I'm unsure where exactly they should be set. 我不确定应该在哪个表上放置外键等等...我一直在尝试尝试不同的组合,但是我不确定应该在哪里设置它们。

  2. I would like to be able to to query the posts table and get all the tags, the author, the category and comments in a single query. 我希望能够查询posts表并在单个查询中获取所有标签,作者,类别和评论。 An example would be good. 一个例子会很好。

NB I don't have any issues with syntax, this is more logistics than anything else, pseudo-code would be fine. 注意:我在语法上没有任何问题,这比其他任何事情都更可取,伪代码会很好。

Your tables should look like this: 您的表应如下所示:

posts ( 
   id, 
   author_id, 
   category_id, 
   message 
) 

comments ( 
   id, 
   post_id, 
   message
)

authors ( 
   id, name
) 

categories ( 
   id, name   
) 

tags ( 
   id, tag 
) 

tags_to_posts ( 
   tag_id, 
   post_id 
)

And here is the mysql query to get all the data you want: 这是用于获取所需所有数据的mysql查询:

SELECT
   posts.id,
   tags.id,
   posts.message,
   comments.message AS comment,
   tags.tag,
   categories.name AS categorie,
   authors.name AS author
FROM posts
JOIN tags_to_posts ON posts.id = tags_to_posts.post_id
JOIN comments ON posts.id = comments.post_id
JOIN tags ON tags.id = tags_to_posts.tag_id 
JOIN categories ON categories.id = posts.category_id
JOIN authors ON authors.id = posts.author_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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