使用LEFT JOIN与OR时,MySQL查询忽略索引?

时间:2011-08-05 14:38:45

标签: mysql indexing ignore

我有这个问题:

SELECT f.uid, fi.status FROM friends f
LEFT JOIN friends_invitations fi ON f.fid = fi.fid
WHERE (f.uid = 2 OR fi.uid = 2)

上面的查询是正确的,但是在性能方面它会扫描friends表中的所有行,并忽略WHERE子句中的f.uid索引,尽管fid和uid是BOTH表中的索引。

基本上我想要使用'uid'字段检索Friends或Friends Invitations表中存在的用户的最佳方法。

有任何想法/建议吗?

3 个答案:

答案 0 :(得分:2)

怎么样:

SELECT f.uid, fi.status 
FROM friends f 
LEFT JOIN friends_invitations fi ON f.fid = fi.fid 
WHERE (f.uid = 2) 
UNION
SELECT f.uid, fi.status 
FROM friends f 
INNER JOIN friends_invitations fi ON f.fid = fi.fid 
WHERE fi.uid = 2

或者左连接的组合使您的查询全扫描

答案 1 :(得分:0)

使用UNION:

SELECT f.uid FROM friends f WHERE f.uid = 2
UNION
SELECT f.uid FROM friends f
JOIN f.friends_invitations fi ON f.fid = fi.fid
WHERE fi.uid = 2

答案 2 :(得分:0)

SELECT u.uuid, fi2.status FROM
( SELECT f.uid AS uuid FROM friends AS f WHERE f.uid = 2
  UNION
  SELECT fi.uid FROM friends_invitations AS fi WHERE fi.uid = 2 ) AS u
LEFT JOIN friends_invitations AS fi2 WHERE u.uuid = fi2.uid