Querying 2 Tables in a single query

后端 未结 3 1567
梦如初夏
梦如初夏 2020-12-21 16:02

I have a table for posts and a table for categories, what i want is to select posts that are in a specific category. The problem is that the category is stored in another ta

3条回答
  •  不知归路
    2020-12-21 16:22

    Use:

    SELECT p.id,
           p.title, 
           p.body
      FROM POSTS p
      JOIN CATEGORIES c ON c.postid = p.id
     WHERE c.category = 'politic'
    

    The issue I have with your CATEGORIES table is that storing the category value as a string means the data isn't normalized - you should instead have a CATEGORY table:

    CATEGORY

    • category_id (primary key, auto_increment)
    • category_description

    ...and use the category_id value in the CATEGORIES table:

    CATEGORIES

    • category_id (primary key, foreign key to CATEGORY.category_id)
    • post_id (primary key, foreign key to POSTS.postid)

提交回复
热议问题