版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26437925/article/details/83154050
学生,课程,成绩三张表
mysql> desc test_user;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| username | varchar(50) | YES | MUL | NULL | |
| email | varchar(30) | YES | | NULL | |
| password | varchar(32) | YES | | NULL | |
| status | tinyint(1) | YES | | 0 | |
| no | int(11) | YES | MUL | 0 | |
+----------+-------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)
mysql> desc test_score;
+-----------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| user_id | bigint(20) | YES | | NULL | |
| cource_id | bigint(20) | YES | | NULL | |
| score | int(11) | YES | | NULL | |
+-----------+------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
没有外键关联
出现如下的子查询,测试非常耗时
观察如下的几个查询,不同的语句查询时间差距比较大,join的效率比子查询,全表查效率要好不少。
select user_id, score from test_score where user_id in (select id from test_user where id < 100);
mysql> select user_id, score from test_score where user_id in (select id from test_user where id < 10);
+---------+-------+
| user_id | score |
+---------+-------+
| 1 | 46 |
| 2 | 78 |
| 3 | 51 |
| 4 | 21 |
| 5 | 54 |
| 6 | 6 |
| 7 | 70 |
| 8 | 30 |
| 9 | 41 |
+---------+-------+
9 rows in set (2.06 sec)
mysql>
mysql> select user_id, score from test_score join test_user using(id) where id < 10;
+---------+-------+
| user_id | score |
+---------+-------+
| 1 | 46 |
| 2 | 78 |
| 3 | 51 |
| 4 | 21 |
| 5 | 54 |
| 6 | 6 |
| 7 | 70 |
| 8 | 30 |
| 9 | 41 |
+---------+-------+
9 rows in set (0.00 sec)
mysql>
mysql> select user_id, score from test_score,test_user where test_score.user_id = test_user.id and test_user.id < 10;
+---------+-------+
| user_id | score |
+---------+-------+
| 1 | 46 |
| 2 | 78 |
| 3 | 51 |
| 4 | 21 |
| 5 | 54 |
| 6 | 6 |
| 7 | 70 |
| 8 | 30 |
| 9 | 41 |
+---------+-------+
9 rows in set (2.19 sec)
mysql>
-
参考
sql的7中join: https://www.cnblogs.com/dinglinyong/p/6656315.html