这里是我的查询:如何用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'子句。这是多余的,因为它在子查询中。 –