[toc]
select高级用法
1.多表连接查询
select 表1.列名,表2.列名 from 表1,表2 where 表1.列1=表2.列1 and 表1.列2=值
1.1 创建两张表
mysql> create table t1(id int,name char(20));
Query OK, 0 rows affected (0.02 sec)
mysql> create table t2(id int,age tinyint);
Query OK, 0 rows affected (0.02 sec)
1.2 向表中插入数据
mysql> insert into t1 values(1,'aaa'),(2,'bbb'),(3,'ccc');
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> insert into t2 values(1,25),(2,26),(3,27);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
1.3 查询t1、t2表中id为1的人的年龄
mysql> select t1.name,t2.age from t1,t2 where t1.id=t2.id and t1.id=1;
+------+------+
| name | age |
+------+------+
| aaa | 25 |
+------+------+
1 row in set (0.00 sec)
2.sql join连接
2.1 sql join连接示意图
下图展示了 LEFT JOIN、RIGHT JOIN、INNER JOIN、OUTER JOIN 相关的 7 种用法
2.2 sql数据准备
2.2.1 创建一个人名表和地址表
1.创建一个数据库
mysql> create database DB1 charset utf8 collate=utf8_general_ci;
Query OK, 1 row affected (0.01 sec)
2.创建人名表
mysql> create table person(person_id int,name varchar(20));
Query OK, 0 rows affected (0.02 sec)
3.创建地址表
mysql> create table address(address_id int,person_id int,city varchar(20));
Query OK, 0 rows affected (0.02 sec)