duanbipu7601 2015-03-27 15:55
浏览 36
已采纳

从多类别获取帖子(没有wordpress,纯php和mysql)

There are 2 MySQL tables: 'posts' and 'category'. Unfortunately there is no taxonomy table.

Categories:

id: integer
name: string

Posts:

id: integer
name: string
body: text
tag: string
category: string

So, in category there is:

 id    name
 1     Books
 2     Animals

And Post:

 id    name     body      tag      category
 1     My Post  Hi post   my-post  1
 2     Post 2   2nd Post  post-2   1;2

This is te SQL query:

SELECT * FROM posts WHERE category = '1'

Only returns post id 1

SELECT * FROM posts WHERE category = '2'

Returns nothing

How can I get both posts with just one SQL query?

  • 写回答

1条回答 默认 最新

  • douxing1353 2015-03-27 16:13
    关注

    Personally, I would steer well clear of that structure and create a new table PostCategoryto house your associated categories for each post so:

    postID | categoryID
    1      | 1
    2      | 1
    2      | 2
    

    Then use a distinct select and an inner join in your sql:

    select distinct post.* from post 
    inner join postcategory on post.id = postcategory.postID 
    where postcategory.categoryID = 2;
    

    As @McAdam331 quite rightly said, using a string to store lookup values you're going to be querying is B.A.D for performance and in general for db design

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来