dounao4179 2016-08-09 14:26
浏览 5
已采纳

PHP选择类别和计数

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 ', '. How to do that is searched when category = category ID and show counter with a minimum of SQL queries.

  • 写回答

1条回答 默认 最新

  • duanqian3464 2016-08-09 14:31
    关注

    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. 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.
    • Queries using the column cannot be optimized using indexes.

    You should have a table called PostCategories for this information.

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用