标签:
1.数据准备
mysql> select * from student;
+----+--------+----------+---------+-------------+
| id | name | idCardNo | isCadre | nickname |
+----+--------+----------+---------+-------------+
| 1 | Tom | 350020 | 1 | Big T |
| 2 | Jim | 350022 | NULL | PP |
| 3 | Lucy | 460311 | NULL | Little girl |
| 4 | Liming | 733098 | 1 | NULL |
+----+--------+----------+---------+-------------+
mysql> select * from cadre;
+----+--------+----------+-----------+
| id | name | idCardNo | nickname |
+----+--------+----------+-----------+
| 1 | Tom | 350020 | Last Tom |
| 2 | Max | 636095 | Hand |
| 3 | Liming | 733098 | China Boy |
+----+--------+----------+-----------+
要求:查询出student表中所有人员信息及其在cadre表中的nickname
① 子查询方式
SELECT a.idcardNo, a.name, a.nickname, (SELECT b.nickname FROM cadre b WHERE b.name=a.name) AS nickname_b FROM student a;
+----------+--------+-------------+------------+
| idcardNo | name | nickname | nickname_b |
+----------+--------+-------------+------------+
| 350020 | Tom | Big T | Last Tom |
| 350022 | Jim | PP | NULL |
| 460311 | Lucy | Little girl | NULL |
| 733098 | Liming | NULL | China Boy |
+----------+--------+-------------+------------+
子查询的方式中,针对student表的每条记录都会对cadre表进行一次查询,效率较低。
② 使用JOIN优化方式
SELECT a.idCardNo, a.name, a.nickname, b.nickname FROM student a LEFT JOIN cadre b ON a.name=b.name;
+----------+--------+-------------+-----------+
| idCardNo | name | nickname | nickname |
+----------+--------+-------------+-----------+
| 350020 | Tom | Big T | Last Tom |
| 733098 | Liming | NULL | China Boy |
| 350022 | Jim | PP | NULL |
| 460311 | Lucy | Little girl | NULL |
+----------+--------+-------------+-----------+
标签:
原文地址:http://www.cnblogs.com/techroad4ca/p/5738643.html