【问题标题】:How to setup foreign keys/queries on multiple tables如何在多个表上设置外键/查询
【发布时间】:2015-11-12 10:21:38
【问题描述】:

我正在尝试为博客设置数据库,它有以下表格:

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,
)

基本思路是这样的:

 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. 我不确定应该将外键放在哪些表上等等...我一直在尝试尝试不同的组合,但我不确定它们应该设置在哪里。

  2. 我希望能够查询帖子表并在单个查询中获取所有标签、作者、类别和 cmets。举个例子就好了。

请注意,我对语法没有任何问题,这比其他任何事情都更加后勤,伪代码就可以了。

【问题讨论】:

    标签: mysql join foreign-keys


    【解决方案1】:

    您的表格应如下所示:

    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 
    )
    

    这里是获取你想要的所有数据的 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;
    

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多