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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历