我正在尝试为博客设置数据库,它有以下表格:
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
我不确定哪些表格应该把外键放在等等......我一直在尝试尝试不同的组合但是我不确定它们应该在哪里设置
我希望能够查询posts表并在单个查询中获取所有标签,作者,类别和注释。一个例子就是好的。
N.B我没有任何语法问题,这比其他任何事情都更加物流,伪代码就没问题了。
答案 0 :(得分:0)
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:
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;