這裏是我的查詢:如何用UNION運算符替換OR運算符?
SELECT
h.id,
h.subject,
h.body matnF,
h.amount,
h.keywords tags,
h.closed,
h.author_id author,
h.AcceptedAnswer,
h.type,
h.visibility,
h.date_time,
v.value AS vote_value,
u.reputation,
u.user_fname,
u.user_lname,
u.avatar,
(h.author_id = user_id1) as hasUserId,
(select COALESCE(sum(vv.value), 0)
from votes vv
where h.id = vv.post_id and vv.table_code = '$this->table_code'
) as total_votes,
(select count(1)
from favorites ff
where h.type = 0 and h.id = ff.post_id and ff.table_code = '$this- >table_code'
) as total_favorites,
CASE WHEN h.type = 1 THEN '0'
WHEN h.amount IS NULL OR h.author_id = :user_id2 THEN '1'
ELSE EXISTS(select 1
from money m
where m.user_id = :user_id3 and m.post_id = h.id
)END paid,
CASE WHEN h.type = 0 AND f.id IS NOT NULL THEN '2'
ELSE '3'
END AS favorite
FROM qanda h
LEFT JOIN votes v ON h.id = v.post_id AND v.user_id = :user_id4 AND v.table_code = '$this->table_code'
LEFT JOIN favorites f ON h.type = 0 AND h.id = f.post_id AND f.user_id = :user_id5 AND f.table_code = '$this->table_code'
LEFT JOIN users u ON h.author_id = u.id and h.visibility = 1
WHERE h.id = :id1 OR h.related = :id2
ORDER BY h.type , h.AcceptedAnswer DESC , h.date_time
LIMIT 20;
請關注這一線之上的查詢:
WHERE h.id = :id1 OR h.related = :id2
正如你看到的,有這兩個條件之間OR
邏輯運算符。如您所知,OR
通常會阻止有效使用索引。所以當有大量數據時,我的查詢性能非常弱。
我該如何改進?其實我試圖用UNION
替換OR
,但正如你看到我的查詢太長了..那麼有什麼想法嗎?
編輯:這裏是EXPLAIN
結果:(一個非常短的數據集 - 在整個20行)
嗯,我知道了有些..給予好評 –
但發生了什麼'WHERE'條款我的查詢?也是的,通常選擇幾行*(最多5行)* ..!可否請將您的想法應用到我的原始查詢中並將其添加到您的答案中? –
@Stack。 。 。你會刪除'where'子句。這是多餘的,因爲它在子查詢中。 –