0

I'm trying to retrieve data from 2 tables and combine multiple rows into a single while loop

posts

post_id content          
------  -------      
   1    content1                     
   2    content2           
   3    content3  
   4    content4


comments

id      post_id   content   
------  ------    ------              
   1      1        Wharton university           
   1      2        Yale University         

sql code I write

    mysqli_query( $connect, "SELECT * FROM `posts`
 INNER JOIN  comments ON posts.post_id =  comments.post_id  ORDER BY 1 DESC");

The problem I'm only getting post id 1 and 2. while there are over 30 posts

I want to get all posts and comments for each post in a single while loop.

How can I do it ?

3
  • what is jquery's role in this question? Commented May 24, 2016 at 3:56
  • is to get all columns data from both tables! , do I have to name each column ? Commented May 24, 2016 at 3:59
  • there are over 30 posts, and how many comments? For your case, IMO you should use left outer join instead of inner join Commented May 24, 2016 at 4:04

2 Answers 2

2

Change your join to a LEFT join instead of an INNER join.

The difference being that a LEFT join will use null when there's no comments, where as INNER will only give you the rows that have comments.

Sign up to request clarification or add additional context in comments.

Comments

1

Your INNER join is taking the union of both tables on the post_id field. You need a LEFT join instead of an INNER join. The LEFT join will give you all the results from the first table.

1 Comment

Actually, when I started my post, there were no posts. I don't really think I need to copy an extremely elementary SQL concept. Don't get so defensive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.