我有两个表叫 1. 表 A - 多列,主键为 user_id(900,000 多条记录) 2. 表 B - 具有名为 user_id 的单列(900 多条记录)
表A包含表B的所有user_id等等。我需要通过 user_id 获取匹配 A、B 行的 * 列的列表。我正在使用以下查询,它已经在我的 p4 机器上以 100% CPU 运行了 1 小时,但看不到任何结果。
SELECT a.* FROM tableA AS a INNER JOIN tableB AS b ON a.user_id = b.user_id;
有没有办法使查询执行得更快?
最佳答案
首先确保 tableA
和 tableB
在它们的 user_id
字段上都有索引。
如果标准技术没有帮助,您可以使用 STRAIGHT_JOIN
强制 MySQL 以不同的顺序连接这两个表:
SELECT a.*
FROM tableB AS b /* first process the 900 rows */
STRAIGHT_JOIN tableA AS a /* and find matching rows for every tableB row */
USING user_id; /* BTW, you could use USING here :) */
http://dev.mysql.com/doc/refman/5.0/en/join.html
STRAIGHT_JOIN is similar to JOIN, except that the left table is always read before the right table. This can be used for those (few) cases for which the join optimizer puts the tables in the wrong order.
其他信息:http://dev.mysql.com/doc/refman/5.0/en/left-join-optimization.html
... The table read order forced by LEFT JOIN or STRAIGHT_JOIN ...
For a LEFT JOIN, if the WHERE condition is always false for the generated NULL row, the LEFT JOIN is changed to a normal join.
关于mysql - 如何使内部连接高效的mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814994/