简体   繁体   English

在php / mysql中的sql查询中有多个类别和一个帖子

[英]Multiple categories with one posts in sql query in php/mysql

I Made two tables 我做了两张桌子

  1. posts 帖子
  2. categories 分类

In posts table I created category column, here I store multiple category_id like this 1,2,3 . 我在posts表中创建了category列,在这里存储了多个1,2,3这样的category_id。

The problem is if category column has single category_id like 1 or 2 or 3 , I can easily query the data like this: 问题是,如果category列具有单个category_id,例如123 ,我可以轻松地查询如下数据:

SELECT title FROM posts WHERE category = $category_id

However, I am unsure as to how to query the comma-delimited data. 但是,我不确定如何查询逗号分隔的数据。 Is there a way to do this, or should I change the table structure ? 有没有办法做到这一点,还是应该更改表结构?

您可以创建一个联结表(可能使用EAV设计 ),也可以保留唯一的表并使用FIND_IN_SET ,如下所示:

SELECT title FROM posts WHERE FIND_IN_SET(1, category) > 0

在此处输入图片说明

Here you can have: Categoryid: 1 Postid: 1,2,3 在这里您可以拥有:Categoryid:1 Postid:1,2,3

Result = Categoryid: 1 --> Postid 1,2,3 结果= Categoryid:1-> Postid 1,2,3

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

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