0

TABLE1

ID | NAME
1  | a   
2  | b  
3  | c  
4  | d  

TABLE2

ID | TBL1_ID | NAME  
1  | 2       | x     
2  | 2       | y  
3  | 2       | z  

I would like to join two tables to get all records from table 1 and all records joined from table 2 on ID

This query return only all rows from 1 table and 1 row from second table.

SELECT  a.*, COUNT(a.id) total FROM table1 a  
  LEFT JOIN table2 b ON a.id = b.tbl1_id    
  GROUP BY a.id  
  ORDER BY a.id DESC  

Thanks.

2 Answers 2

1
SELECT  * total FROM table1 a  
  left JOIN table2 b ON a.id = b.tbl1_id   
Sign up to request clarification or add additional context in comments.

Comments

1

If You need to join both tables and show all fields on matching rows this should work:

SELECT  * FROM table1 a  
  LEFT JOIN table2 b ON(a.id = b.tbl1_id)

4 Comments

You can't use USING here as the join column in the second table is tbl1_id.
Would it join all rows from table2?
Now I have joined all rows from table1 + first row from table2
@miojamo, It will take every row from table1 and stick it with every matching row (if exists) from table2, so in Your example the result will be: 1-a-null, 2-a-x, 2-a-y, 2-a-z, 3-c-null, 4-d-null

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.