2016-02-26 189 views
2

我有一個問題,例如我有三個表tbldispensaries,tblStates,tblCountries。我將國家和州ID存儲在藥房表中,所有與國家和州相關的細節分別在tblCountriestblStatesMySQL左連接需要太長的時間才能返回

我正在寫一個查詢,以查找500範圍內的附近藥房,以便在Google地圖上顯示標記,查詢很好,但是當我使用與查詢左連接時,它花費的時間太多回復。我嘗試過使用索引,但是它對它也沒有影響。所以請建議我解決這個問題。這裏下面是我正在使用的查詢: -

SELECT 
    d.id AS disp, 
    d.id AS the_id, 
    d. NAME, 
    d.address AS addr, 
    d.city AS city_name, 
    c.country_name AS cntry_name, 
    s.state_name AS st_name, 
    d.zip AS zipcode, 
    d.latitude, 
    d.longitude, 
    (
     6371 * ACOS(
      COS(RADIANS(33.6119)) * COS(RADIANS(latitude)) * COS(
       RADIANS(longitude) - RADIANS(- 111.8906) 
      ) + SIN(RADIANS(33.6119)) * SIN(RADIANS(latitude)) 
     ) 
    ) AS distance 
FROM 
    `tblDispensaries` d 
    LEFT JOIN tblCountries c ON (c.country_id = d.country) 
    LEFT JOIN tblStates s ON (s.state_id = d.state) 
WHERE 
    d.id IS NOT NULL 
    AND d. STATUS = 1 
HAVING distance < 500 
LIMIT 0,60 
+0

在表 – Priyanshu

+0

的ID列上創建索引我已經在國家和州的tbldispersaries中創建了兩個索引。 –

+0

請分享與我們一起查詢的解釋以及基礎表的create table statemenst,以便我們可以確切地看到您在3個表上的索引。但是,having子句中的過濾可能是查詢速度慢的原因之一。您是否考慮過使用計算列(如果您的mysql版本支持它們)並將條件從where條件移入? – Shadow

回答

0

這可能不是一個答案,但它是一個評論兩大。另外,我沒有數據,所以我無法測試,但在這裏。

SELECT 
    Dispensaries.*, 
    c.country_name AS cntry_name, 
    s.state_name AS st_name 
FROM (
    SELECT 
     d.id AS disp, 
     d.id AS the_id, 
     d. NAME, 
     d.address AS addr, 
     d.city AS city_name, 
     d.zip AS zipcode, 
     d.latitude, 
     d.longitude, 
     (
      6371 * ACOS(
       COS(RADIANS(33.6119)) * COS(RADIANS(latitude)) * COS(
        RADIANS(longitude) - RADIANS(- 111.8906) 
      ) + SIN(RADIANS(33.6119)) * SIN(RADIANS(latitude)) 
     ) 
    ) AS distance 
    FROM 
     `tblDispensaries` d 
    WHERE 
     d.id IS NOT NULL 
     AND d. STATUS = 1 
    HAVING distance < 500 
    LIMIT 0,60 
) as Dispensaries 
LEFT JOIN tblCountries c ON (c.country_id = Dispensaries.country) 
LEFT JOIN tblStates s ON (s.state_id = Dispensaries.state) 

我想提取結果和使用JOIN會更快。

相關問題