Limit columns in right table in LEFTJOIN in MySQL

I have the following 2 tables.

PostId, PostName

PostId, PostCategoryName


I want to join both of these tables, however I would like to display all columns and records in tb_Posts, but only show PostCategoryName columns from tb_PostCategories, even if the entry for tb_Posts.PostId in tb_PostCategories exists or not.

So I made this query but I am getting SQL error

(SELECT a.PostId, a.PostName from tb_Posts a) y
LEFT JOIN tb_PostCategories z USING (y.PostId)




source to share

1 answer


gets all columns.
You can do:

SELECT y.*, z.PostCategoryName
  FROM (SELECT a.PostId, a.PostName FROM tb_Posts a) y
       LEFT JOIN tb_PostCategories z 
       ON y.PostId = z.PostId;


It doesn't really require a subquery, so to keep things simpler:

SELECT posts.*, cat.PostCategoryName
  FROM tb_Posts posts
       LEFT JOIN tb_PostCategories cat
       ON cat.PostId = posts.PostId;




All Articles