mysql数据库常用的查询语句(多表查询)
2013-10-27 16:05
525 查看
1 内连接查询
select 字段1,字段2 from 表1,表2 where 表1.字段3=表2.字段3; //要有相同的字段3 查询的是具有相同的字段3值 (注:表1 inner join 表2 中间的inner on一般可以省略)例如:
原表country
mysql> select * from country;
+----+----------+------------+------+----------+
| id | name | population | area | language |
+----+----------+------------+------+----------+
| 1 | mySQL | 13 | 960 | chinese |
| 2 | American | 4 |60 | English |
| 3 | Japan | 89 | 30 | Jpanese |
| 4 | England | 2 | 300 | English |
+----+----------+------------+------+----------
原表library
mysql> select * from library;
+----+---------------+--------+-------+
| id | name | author | price |
+----+---------------+--------+-------+
| 1 | java范例大全 | 张帆 | 99 |
| 2 | mySQL | 潘凯华 | 50 |
| 3 | SQLserver2005 | 刘智勇 | 80 |
| 4 | mySQL | 李慧 | 50 |
+----+---------------+--------+-------+
mysql> select area,author from country,library where country.name=library.name;
+------+--------+
| area | author |
+------+--------+
| 960 | 潘凯华 |
| 960 | 李慧 |
+------+--------+
2 左外连接
mysql> select language,area,author from country left join library on country.name=library.name; //返回的结果除内连接的数据外,还包括左表中不符合条件数据+----------+------+--------+
| language | area | author |
+----------+------+--------+
| chinese | 960 | 潘凯华 |
| chinese | 960 | 李慧 |
| English | 60 | NULL |
| Jpanese | 30 | NULL |
| English | 300 | NULL |
+----------+------+--------+
3 右外连接
mysql> select language,area,author from country right joinlibrary on country.name=library.name; // //返回的结果除内连接的数据外,还包括右表中不符合条件数据+----------+------+--------+
| language | area | author |
+----------+------+--------+
| NULL | NULL | 张帆 |
| chinese | 960 | 潘凯华 |
| NULL | NULL | 刘智勇 |
| chinese | 960 | 李慧 |
+----------+------+--------+
4 复合条件连接查询
mysql>select population,area,author,price from country,library where country.name=library.name and price>30;5 子查询
1 带IN关键字的子查询
mysql> select * from country wherename in(select name from library);相关文章推荐
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- source命令执行SQL脚本文件
- linux下mysql添加用户
- mysql procedure
- mysql触发器
- MySQL 备份和恢复策略
- mac下安装mysql(转载)
- mysql 修改编码 Linux/Mac/Unix/通用(杜绝修改后无法启动的情况!)
- MySQL数据的导出、导入(mysql内部命令:mysqldump、mysql)
- mysql数据行转列
- Linux下修改MySQL编码的方法
- MySQL Server 日志
- MySQL 安全事宜
- MySQL 备份与恢复
- MySQL 优化
- MySQL 数据类型
- Facebook's New Real-time Messaging System: HBase to Store 135+ Billion Messages a Month
- MySQL复制