繁体   English   中英

从多个类别获取帖子(没有wordpress,纯php和mysql)

[英]Get posts from multi category (no wordpress, pure php and mysql)

MySQL有2个表格:“帖子”和“类别”。 不幸的是,没有分类表。

分类:

id: integer
name: string

帖子:

id: integer
name: string
body: text
tag: string
category: string

因此,在类别中有:

 id    name
 1     Books
 2     Animals

并发布:

 id    name     body      tag      category
 1     My Post  Hi post   my-post  1
 2     Post 2   2nd Post  post-2   1;2

这是SQL查询:

SELECT * FROM posts WHERE category = '1'

仅返回帖子ID 1

SELECT * FROM posts WHERE category = '2'

什么都不返回

我如何只用一个SQL查询就可以得到两个帖子?

就我个人而言,我将完全避开该结构,并创建一个新表PostCategory来容纳每个帖子的关联类别,以便:

postID | categoryID
1      | 1
2      | 1
2      | 2

然后在您的sql中使用不同的select和内部联接:

select distinct post.* from post 
inner join postcategory on post.id = postcategory.postID 
where postcategory.categoryID = 2;

正如@ McAdam331正确地说的那样,使用字符串存储要查询的查找值对于性能而言通常是有害的,对于数据库设计而言通常如此

暂无
暂无

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

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