您好,请您告诉我哪一个更优化:
select a.*,b.* from a join b on a.id=b.id and a.name='test';
select a.*,b.* from a join b on a.id=b.id where a.name='test';
由于
答案 0 :(得分:2)
在我看来,语法良好,如果不是那些'并且之后有一系列WHERE子句,则更容易阅读查询。
由于您使用内部联接,因此两者之间没有区别。内部联接仅显示联接中存在完全匹配的位置。
如果你要使用左连接,事情会有所不同。
答案 1 :(得分:1)
在最简单的情况下,两者都是等价的。为了证明,你可以看看两个执行计划
explain select a.*,b.* from a join b on a.id=b.id and a.name='test'
给出
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
| 1 | SIMPLE | a | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
| 1 | SIMPLE | b | ALL | NULL | NULL | NULL | NULL | 1 | Using where; Using join buffer |
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
2 rows in set (0.00 sec)
然后是
explain select a.*,b.* from a join b on a.id=b.id where a.name='test'
也给出了
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
| 1 | SIMPLE | a | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
| 1 | SIMPLE | b | ALL | NULL | NULL | NULL | NULL | 1 | Using where; Using join buffer |
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
2 rows in set (0.00 sec)