从多类别获取帖子(无wordpress、纯php和mysql)
MySQL有两个表:“posts”和“category”。不幸的是,没有分类表 类别:从多类别获取帖子(无wordpress、纯php和mysql),php,mysql,sql,post,categories,Php,Mysql,Sql,Post,Categories,MySQL有两个表:“posts”和“category”。不幸的是,没有分类表 类别: 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 P
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查询:
从类别为“1”的帖子中选择*
仅返回post id 1
从类别为'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非常正确地说的,使用字符串存储要查询的查找值是对性能的B.a.D,通常是对db设计的B.a.D.这是一种非常糟糕的存储类别的方法。你可以使用
LIKE
关键字来尝试并完成你想要的,但是你会很快发现这种方法有很多缺陷。例如,如果我说'WHERE category,比如'%1%',我将得到任何一个1:1,11,12,13…,21..的类别。。等等从你设计htis的方式很难区分单个1。我知道,当我第一次看到它时就是这样。我试过像这样的,但它会返回category 1、category 11、category 111等等。这太完美了。我真的很高兴有人花时间演示新桌子的样子。作为其他人的参考,请参见“谢谢各位”,这似乎是一个更好的解决方案