多重表格聯合查詢 子查詢 條件查詢 排序
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有問題。問題在於csp_auction_car表有多少筆記錄,csp_auction_record表就被掃描了多少次。想想就覺得可怕,但我確實看到很多人喜歡這麼寫。還有,where條件盡量寫在子查詢裡面,ac表的資料量查出來會減少很多,跟後面的關聯會更快。
可以改成下面這樣,csp_auction_record表只掃描1次