php - sql 語句寫成這個樣子有效能問題嗎? ?如何改進? ?
高洛峰
高洛峰 2017-05-24 11:30:34
0
1
632

多重表格聯合查詢 子查詢 條件查詢 排序

SELECT
  ac.*,
  c.car_number,
  c.car_name,
  cs.car_source,
  cb.brand_name,
  cm.car_model,
  ct.car_type,
  c.number_plate,
  (
  SELECT
    COUNT(ar.auction_record_id)
  FROM
    csp_auction_record AS ar
  WHERE
    ac.auction_car_id = ar.auction_car_id
) AS auction_count
FROM
  csp_auction_car AS ac
INNER JOIN
  csp_car AS c
ON
  ac.car_id = c.car_id
INNER JOIN
  csp_car_brand AS cb
ON
  c.car_brand_id = cb.car_brand_id
INNER JOIN
  csp_car_source AS cs
ON
  c.car_source_id = cs.car_source_id
INNER JOIN
  csp_car_type AS ct
ON
  c.car_type_id = ct.car_type_id
INNER JOIN
  csp_car_model AS cm
ON
  c.car_model_id = cm.car_model_id
WHERE
  ac.auction_s_time <= CURRENT_TIMESTAMP AND ac.auction_e_time >= CURRENT_TIMESTAMP
ORDER BY
  ac.auction_car_id
DESC
LIMIT 0, 10

相關資料表:

csp_car_brand,車輛品牌表:

#csp_car_type,車輛類型表:

#csp_car_source,車輛來源表:

#csp_car_model,車輛型號表(所屬品牌的特定型號):

##csp_car,車輛表(這張表格欄位太多,只列出部分)

#csp_auction_record,拍賣紀錄表:

#請問這 sql 語句有效能問題嗎? ?該如何優化? ?是用 php 來拆成一條簡單sql語句,然後將結果組合,還是怎樣? ?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(1)
phpcn_u1582

既然你這麼問了,就表示你知道自己的sql有問題。問題在於csp_auction_car表有多少筆記錄,csp_auction_record表就被掃描了多少次。想想就覺得可怕,但我確實看到很多人喜歡這麼寫。還有,where條件盡量寫在子查詢裡面,ac表的資料量查出來會減少很多,跟後面的關聯會更快。
可以改成下面這樣,csp_auction_record表只掃描1次

SELECT ac.*,
       c.car_number,
       c.car_name,
       cs.car_source,
       cb.brand_name,
       cm.car_model,
       ct.car_type,
       c.number_plate,
       IFNULL(ar.count, 0) AS auction_count
  FROM (select *
          from csp_auction_car
         WHERE auction_s_time <= CURRENT_TIMESTAMP
           AND auction_e_time >= CURRENT_TIMESTAMP) AS ac
 INNER JOIN csp_car AS c
    ON ac.car_id = c.car_id
 INNER JOIN csp_car_brand AS cb
    ON c.car_brand_id = cb.car_brand_id
 INNER JOIN csp_car_source AS cs
    ON c.car_source_id = cs.car_source_id
 INNER JOIN csp_car_type AS ct
    ON c.car_type_id = ct.car_type_id
 INNER JOIN csp_car_model AS cm
    ON c.car_model_id = cm.car_model_id
  left outer join (select auction_car_id, count(*) count
                     from csp_auction_record
                    group by auction_car_id) ar
    on ac.auction_car_id = ar.auction_car_id
 ORDER BY ac.auction_car_id DESC LIMIT 0, 10

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板