I have two tables –
tbl_business
------------------------
| id | name | lat |long|
|----|------|-----|----|
| 1 | aaaa |12.45|6.88|
|----|------|-----|----|
| 2 | bbbb |12.34|6.45|
|----|------|-----|----|
| 3 | cccc |12.12|6.50|
|----|------|-----|----|
and
tbl_deals
-------------------
| id | deal | bid |
|----|------|-----|
| 1 | xxxx | 1 |
|----|------|-----|
| 2 | yyyy | 1 |
|----|------|-----|
| 3 | zzzz | 2 |
|----|------|-----|
Now I want to find all the businesses that are within 1km of 12.44, 6.66, along with the deals count. E.g.
| bid |dcount|
|-----|------|
| 1 | 2 |
|-----|------|
| 2 | 1 |
|-----|------|
| 3 | 0 |
|-----|------|
I’m using this query right now –
SELECT bid, COUNT( id ) as count
FROM `tbl_deals`
WHERE bid
IN (
SELECT id
FROM tbl_business
WHERE ( 6371 * ACOS( COS( RADIANS( 12.44 ) ) * COS( RADIANS( lat ) ) * COS( RADIANS( long ) - RADIANS( 6.66 ) ) + SIN( RADIANS( 12.44 ) ) * SIN( RADIANS( lat ) ) ) ) < 1
)
GROUP BY bid
ORDER BY count DESC
I found the formula here. But this doesn’t show count = 0 for bid 3. I’m guessing I have to use Left join for this, but cannot figure out how.
Yes, you have to write an outer join, a
business LEFT JOIN deals: