简体   繁体   English

如何根据类别匹配从数据库中选择?

[英]how to select from database based on a match in category?

Is it possible to select certain rows based on a category which matches it when there are multiple categories in the entry? 当条目中有多个类别时,是否可以根据与之匹配的类别选择某些行? It's hard to explain so I'll show you. 很难解释,所以我会告诉你。 The row I have in the database looks like this: 我在数据库中的行如下所示:

**article_title**   |   **article_content**    |    **category**

Article-1           |   some content here      |    one,two,three,four

So my query looks like this: 所以我的查询看起来像这样:

$sql = mysqli_query($mysqli_connect, "SELECT * FROM table WHERE category='
preg_match(for example the word three)'");

Reason why I'm doing that is some articles will be available on multiple pages like page one and page three...so is there a way to match what I'm looking for through the entry in the database row? 我这样做的原因是有些文章可以在第一页和第三页等多个页面上找到...那么有没有办法通过数据库行中的条目来匹配我要寻找的内容?

You should use a more flexible database design. 您应该使用更灵活的数据库设计。 Create a separate table that holds the one-to-many relationships between (one) article and (many) categories: 创建一个单独的表,其中包含(一个)文章和(许多)类别之间的一对多关系:

CREATE TABLE IF NOT EXISTS `articles` (
  `article_id` int(11) NOT NULL AUTO_INCREMENT,
  `article_name` varchar(255) NOT NULL,
  PRIMARY KEY (`article_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

INSERT INTO `articles` (`article_id`, `article_name`) VALUES
(1, 'Research Normalized Database Design');

CREATE TABLE IF NOT EXISTS `article_category` (
  `article_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `article_category` (`article_id`, `category_id`) VALUES
(1, 1),
(1, 2);

CREATE TABLE IF NOT EXISTS `categories` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(255) NOT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `categories` (`category_id`, `category_name`) VALUES
(1, 'Databases'),
(2, 'Normalization');

Querying then becomes as simple as: 这样查询就变得很简单:

SELECT 
    *
FROM 
    articles AS a
JOIN 
    article_category AS pivot ON a.article_id = pivot.article_id 
WHERE 
    pivot.category_id = 2

Or do something like: 或执行类似的操作:

SELECT 
    *
FROM 
    articles AS a
JOIN 
    article_category AS pivot ON a.article_id = pivot.article_id 
JOIN 
    categories AS c ON pivot.category_id = c.category_id
WHERE 
    c.category_name = 'Normalization'

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

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