以下是查询语句:
SELECT
u.uid as UID,
fuo.uid as FUO_UID,
fo.prid as FO_NAME
FROM
users u
LEFT OUTER JOIN firstpoint_users_organisations fuo ON (u.uid=fuo.uid)
LEFT OUTER JOIN firstpoint_organisations fo ON (fo.nid=fuo.nid)
WHERE
u.status=1 AND u.uid>1
ORDER BY u.uid
LIMIT 3;
还有表格:
users
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| uid | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(60) | NO | UNI | | |
| status | tinyint(4) | NO | | 0 | |
+-----------------------------------------------------------------------------+
firstpoint_users_organisations
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| nid | int(10) unsigned | NO | PRI | 0 | |
| uid | int(10) unsigned | NO | PRI | 0 | |
+-------+------------------+------+-----+---------+-------+
firstpoint_organisations
+----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+-------+
| nid | int(10) unsigned | NO | PRI | 0 | |
| prid | varchar(32) | NO | | | |
+------------------------------------------------------------+
我希望在users
表的每一行中显示users.uid
和firstpoint_organisations.prid
,即使有些用户没有prid
,此时应该显示NULL(因此使用左外连接)。连接应该如下:
users
uid - firstpoint_users_organisations
\---->uid
nid - firstpoint_organisations
\-------->nid
prid
每个用户都有一个用户ID(UID),以及他们所关联的组织(firstpoint_users_organisation)的节点ID(NID),并存储此关联。然后,组织的详细信息存储在firstpoint_organisations中。
因此,每个用户都将有一个prid,但如果没有,则显示NULL。
现在,如果我在firstpoint_users_organisations上进行INNER JOIN,然后在firstpoint_organisations上进行JOIN,我会得到很好的查询速度(上面的查询在0.02秒内运行)。但是,当我将两者都切换为LEFT OUTER JOIN时,以便获得所有用户,无论是否有prid,上述查询需要大约90秒才能运行。
有什么方法可以加快此查询速度吗?用户表中大约有70,000行,但即使使用LIMIT 3,将INNER JOIN变为LEFT OUTER JOIN也需要很长时间。有趣的是,查询用时与LIMIT 30相同,因此我认为我的查询存在根本性问题。
如请求的EXPLAIN所示:
+----+-------------+-------+--------+---------------+---------+---------+-----------------------+-------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------+-------+----------------------------------------------+
| 1 | SIMPLE | u | range | PRIMARY | PRIMARY | 4 | NULL | 13152 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | fuo | index | NULL | PRIMARY | 8 | NULL | 3745 | Using index |
| 1 | SIMPLE | fo | eq_ref | PRIMARY | PRIMARY | 4 | dbdb-dbdb_uat.fuo.nid | 1 | |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------+-------+----------------------------------------------+
3 rows in set (0.00 sec)
EXPLAIN
。 - Kermit