简体   繁体   English

PHP选择类别和数量

[英]PHP select categories and count number

Table categories: 表格类别:

id, name,    
-------------
1   category1
2   category2
3   category3
4   category4

Table posts: 表帖子:

id, category, title
--------------------
1   1, 3      title1
2   4, 2      title2
3   1, 4      title3

I would like to have a show categories and counter posts in this category. 我想要一个表演类别和这个类别的反岗位。 In the category column in the table posts I IDs of categories, which are separated by ', '. 在表格的类别列中,我输入了类别ID,这些ID以“,”分隔。 How to do that is searched when category = category ID and show counter with a minimum of SQL queries. 当category = category ID并使用最少的SQL查询显示计数器时,将搜索该方法。

You should fix your data structure to have one row per post and category. 您应该将数据结构固定为每个帖子和类别都有一行。 A comma-separated list is not a SQLish way to store data for many reasons. 出于多种原因,逗号分隔列表不是存储数据的SQLish方法。 You should change this to a junction table. 您应该将其更改为联结表。

Here are some reasons why: 原因如下:

  • Numbers should be stored as numbers and not strings. 数字应存储为数字而不是字符串。
  • Foreign key relationships should be properly defined, and you can't do that with a string to a number. 外键关系应正确定义,并且不能使用数字字符串。
  • An attribute should contain one value. 一个属性应包含一个值。
  • MySQL doesn't have very good support for string processing functions. MySQL对字符串处理功能没有很好的支持。
  • Queries using the column cannot be optimized using indexes. 无法使用索引优化使用该列的查询。

You should have a table called PostCategories for this information. 您应该有一个名为PostCategories的表以获取此信息。

Sometimes, we are stuck with other peoples bad design decisions. 有时,我们陷入别人的错误设计决定中。 If so, you can use a query such as: 如果是这样,则可以使用以下查询:

select c.id, count(*)
from posts p join
     categories c
     on find_in_set(c.id, replace(p.category)) > 0
group by c.id;

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

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