A sql query to fetch data of both table even if related id is not available

1824 views mysql

I have to table ledger and accounthead


id | name   | phone
1  | Saijal | 989898    
2  | Shakya | 878787


id | accid | dr    | cr
1  |  1    | 10000 | 5000

Sql i tried

select * from ledger full join accounthead on accid = accounthead.id 
where accid=1

It gives all result i want but id accid=2 it shows null but i want all information from accounthead even if it has no data in ledger

answered question

2 Answers


RIGHT JOIN is what you need which will return all rows from accounthead table and only matching rows from ledger

SELECT ledger.id AS ledger_id, ledger.accid, ledger.dr, ledger.cr, accounthead.name, accounthead.phone
FROM ledger RIGHT JOIN accounthead
ON ledger.accid = accounthead.id

posted this

You can try to use OUTER JOIN and let accid = 1 in on instead of where

select * 
from ledger RIGHT JOIN accounthead on accid = accounthead.id and accid = 1

posted this

Have an answer?


Please login first before posting an answer.