2012-03-15 56 views
2

我有兩個表 -MySQL的聯接與其中

tbl_business 
------------------------ 
| id | name | lat |long| 
|----|------|-----|----| 
| 1 | aaaa |12.45|6.88| 
|----|------|-----|----| 
| 2 | bbbb |12.34|6.45| 
|----|------|-----|----| 
| 3 | cccc |12.12|6.50| 
|----|------|-----|----| 

tbl_deals 
------------------- 
| id | deal | bid | 
|----|------|-----| 
| 1 | xxxx | 1 | 
|----|------|-----| 
| 2 | yyyy | 1 | 
|----|------|-----| 
| 3 | zzzz | 2 | 
|----|------|-----| 

現在我想找到所有的內12.44, 6.661公里的是,隨着交易統計業務。例如。

| bid |dcount| 
|-----|------| 
| 1 | 2 | 
|-----|------| 
| 2 | 1 | 
|-----|------| 
| 3 | 0 | 
|-----|------| 

我使用這個查詢現在 -

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 

我發現公式here。但是,這並不顯示計數= 0爲出價3.我猜我必須使用左連接這個,但不知道如何。

回答

0

是的,你必須寫一個外連接,一個business LEFT JOIN deals

SELECT 
     b.id 
    , COUNT(d.bid) AS dcount 
FROM 
     tbl_business AS b 
    LEFT JOIN 
     tbl_deals AS d 
    ON 
     d.bid = b.id 
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 
     b.id 
ORDER BY 
     dcount DESC 
+0

這工作。謝謝。我想我應該多學習一些關於連接的知識。 :) 對於初學者可能有的任何資源? (除mysql文檔:P) – 2012-03-15 22:17:51

+2

[http://sql-ex.ru/一個網站與SQL練習](http://sql-ex.ru/) – 2012-03-15 22:39:13

+0

另外:[SQL課程](http:// www .sqlcourse.com/index.html)和[SQL Course 2](http://www.sqlcourse2.com/index.html) – 2012-03-15 22:39:57

0
select id, (select count(*) from tbl_deals,tbl_business a1 where tbl_deals.bid=a1.id and a1.id=a2.id and (6371 * ACOS(COS(RADIANS(12.44)) * COS(RADIANS(lat)) * COS(RADIANS(`long`) - RADIANS(6.66)) + SIN(RADIANS(12.44)) * SIN(RADIANS(lat)))) < 30) as count 
from tbl_business a2 
group by id 
order by count desc 

我使用你的數據和改變條件來滿足結果。

參考: MySQL Group By Count with Zero