MySQL基本SQL查询语句:多表查询和子查询示例

一、简单查询:
基本语法:

 代码如下 复制代码
SELECT * FROM tb_name;

查询全部

 代码如下 复制代码
SELECT field1,field2 FROM tb_name;

投影

 代码如下 复制代码
SELECT [DISTINCT] * FROM tb_name WHERE qualification;

 选择
说明:

FROM子句: 要查询的关系         表、多个表、其它SELECT语句

WHERE子句:布尔关系表达式,主要包含如下这几类表达式:

比较:=、>、>=、<=、<
逻辑关系:
AND
OR
NOT

BETWEEN ... AND ...   :在两个值之间
LIKE ‘’
%: 任意长度任意字符
_:任意单个字符
REGEXP, RLIKE :正则表达式,此时索引无效
IN
IS NULL
IS NOT NULL
 

如下查询本博客的wp-links和wp_posts表:

 代码如下 复制代码

mysql> select * from wp_links; 查询全部 mysql> select link_name,link_url from wp_links; 投影
+-------------------+--------------------------------------+
| link_name               | link_url                                              |
+-------------------+--------------------------------------+
| 旺旺腾讯微博          | http://www.111cn.net              |
| 旺旺新浪微博          | http://weibo.com/gz100ww               |
| 51CTO技术博客      | http://www.111cn.net/ |
+-------------------+--------------------------------------+
10 rows in set (0.00 sec)

mysql> select ID,post_title,post_date from wp_posts where ID>1290 and post_status='publish';选择
+------+----------------------------------------------------------------+----------------------+
| ID   | post_title                                                                                      | post_date                   |
+------+----------------------------------------------------------------+----------------------+
| 1291 | 【转】HP 3PAR存储概念之三                                                      | 2013-08-29 17:21:27 |
| 1298 | 【转】HP 3PAR存储概念之四                                                      | 2013-08-29 17:22:33 |
| 1351 | 【转】XenDesktop 5.5+vSphere 5创建虚拟机报错                      | 2013-09-04 17:41:26 |
| 1357 | linux下强大的网络工具Netcat                                                     | 2013-09-09 22:26:45 |
| 1360 | MySQL常用命令、技巧和注意事项                                              | 2013-09-20 11:04:15 |
| 1369 | 【转】数据库设计原理知识--B树、B-树、B+树、B*树都是什么     | 2013-09-21 12:30:18 |
| 1379 | MySQL基本SQL语句之常用管理SQL                                           | 2013-09-21 12:39:23 |
+------+----------------------------------------------------------------+---------------------+
7 rows in set (0.01 sec)

对查询结果排序:
ORDER BY field_name {ASC|DESC}
如下:

 代码如下 复制代码
mysql> select ID,post_title,post_date from wp_posts where ID>1290 and post_status='publish' ORDER by ID; 

  ##升序,ID是排序的字段

 代码如下 复制代码
mysql> select ID,post_title,post_date from wp_posts where ID>1290 and post_status='publish' ORDER by ID DESC; 

##降序
字段别名:AS
select col_name AS COL_Aliases … :对字段使用别名

select col_name,… from tb_name AS tb_Aliases …  :对表使用别名
如下:

mysql> select post_title AS 文章标题 from wp_posts where ID>1290 and post_status='publish';
+----------------------------------------------------------------+
| 文章标题                                                                                    |
+----------------------------------------------------------------+
| 【转】HP 3PAR存储概念之三                                                      |
| 【转】HP 3PAR存储概念之四                                                      |
| 【转】XenDesktop 5.5+vSphere 5创建虚拟机报错                      |
| linux下强大的网络工具Netcat                                                     |
| MySQL常用命令、技巧和注意事项                                              |
| 【转】数据库设计原理知识--B树、B-树、B+树、B*树都是什么     |
| MySQL基本SQL语句之常用管理SQL                                           |
+----------------------------------------------------------------+
7 rows in set (0.02 sec)

##还可以这样:

 代码如下 复制代码

mysql> select 3+2 AS SUM;
+-----+
| SUM |
+-----+
|   5    |
+-----+
1 row in set (0.00 sec)
LIMIT子句:LIMIT [offset,]Count
如下:

mysql> select ID,post_title,post_date from wp_posts where ID>1290 and post_status='publish' limit 5;
+------+--------------------------------------------------+---------------------+
| ID      | post_title                                                                | post_date               |
+------+--------------------------------------------------+---------------------+
| 1291 | 【转】HP 3PAR存储概念之三                                 | 2013-08-29 17:21:27 |
| 1298 | 【转】HP 3PAR存储概念之四                                 | 2013-08-29 17:22:33 |
| 1351 | 【转】XenDesktop 5.5+vSphere 5创建虚拟机报错  | 2013-09-04 17:41:26 |
| 1357 | linux下强大的网络工具Netcat                                 | 2013-09-09 22:26:45 |
| 1360 | MySQL常用命令、技巧和注意事项                          | 2013-09-20 11:04:15 |
+------+--------------------------------------------------+---------------------+
5 rows in set (0.01 sec)

mysql> select ID,post_title,post_date from wp_posts where ID>1290 and post_status='publish' limit 2,3;  ##红色部分(逗号前的数字)表示偏移量
+------+--------------------------------------------------+---------------------+
| ID      | post_title                                                              | post_date                 |
+------+--------------------------------------------------+---------------------+
| 1351 | 【转】XenDesktop 5.5+vSphere 5创建虚拟机报错  | 2013-09-04 17:41:26 |
| 1357 | linux下强大的网络工具Netcat                                 | 2013-09-09 22:26:45 |
| 1360 | MySQL常用命令、技巧和注意事项                          | 2013-09-20 11:04:15 |
+------+--------------------------------------------------+---------------------+
3 rows in set (0.00 sec)
聚合:SUM(), MIN(), MAX(), AVG(), COUNT(),括号中为字段名
mysql> select sum(ID) from wp_posts;计算和
mysql> select min(ID) from wp_posts;查早最小的
mysql> select max(ID) from wp_posts; 查找最大的
mysql> select avg(ID) from wp_posts; 平均值
mysql> select count(ID) from wp_posts;计数
分组:GROUP BY,一般配合聚合运算使用
如下:

mysql> select count(post_status) AS 各状态数量,post_status AS 状态名称 from wp_posts group by post_status;
+-----------------+--------------+
| 各状态数量           | 状态名称        |
+-----------------+--------------+
|               1           | auto-draft     |
|               9           | draft             |
|             251         | inherit           |
|             238         | publish          |
|               2           | trash             |
+-----------------+--------------+
5 rows in set (0.01 sec)
注意:可以使用HAVING qualification将GROUP BY的结果再次过滤,用法同where

 

二、多表查询
连接:
交叉连接:笛卡尔乘积
自然连接:将两张表某字段中相等连接起来,如下

 代码如下 复制代码
mysql> SELECT students.Name,students.Age,courses.Cname,students.Gender FROM students,courses WHERE students.CID1 = courses.CID;
+--------------+------+------------------+--------+
| Name             | Age   | Cname                 | Gender |
+--------------+------+------------------+--------+
| GuoJing          |   19   | TaiJiquan              | M        |
| YangGuo        |   17   | TaiJiquan              | M        |
| DingDian        |   25   | Qishangquan       | M         |
| HuFei             |   31   | Wanliduxing         | M         |
| HuangRong    |   16   | Qianzhuwandushou | F       |
| YueLingshang |   18   | Wanliduxing         | F          |
| ZhangWuji      |   20   | Hamagong           | M         |
| Xuzhu             |   26   | TaiJiquan              | M         |
+--------------+------+------------------+--------+
8 rows in set (0.00 sec)

    外连接:
左外连接:left_tb LEFT JOIN right_tb ON ...  :以左表为标准

 代码如下 复制代码
mysql> SELECT s.Name,c.Cname FROM students AS s LEFT JOIN courses AS c ON s.CID1=c.CID;
+--------------+--------------------+
| Name             | Cname                    |
+--------------+--------------------+
| GuoJing          | TaiJiquan                 |
| YangGuo        | TaiJiquan                 |
| DingDian        | Qishangquan           |
| HuFei              | Wanliduxing            |
| HuangRong    | Qianzhuwandushou |
| YueLingshang | Wanliduxing            |
| ZhangWuji      | Hamagong              |
| Xuzhu             | TaiJiquan                 |
| LingHuchong  | NULL                      |
| YiLin               | NULL                      |
+--------------+--------------------+
10 rows in set (0.00 sec)

右外连接 : left_tb RIGHT JOIN right_tb ON ... :以右表为标准

 代码如下 复制代码
mysql> SELECT s.Name,c.Cname FROM students AS s RIGHT JOIN courses AS c ON s.CID1=c.CID;
+--------------+--------------------+
| Name             | Cname                    |
+--------------+--------------------+
| GuoJing         | TaiJiquan                  |
| YangGuo       | TaiJiquan                  |
| DingDian       | Qishangquan            |
| HuFei             | Wanliduxing             |
| HuangRong    | Qianzhuwandushou |
| YueLingshang | Wanliduxing            |
| ZhangWuji     | Hamagong               |
| Xuzhu            | TaiJiquan                  |
| NULL             | Yiyangzhi                 |
| NULL             | Jinshejianfa              |
| NULL             | Qiankundanuoyi      |
| NULL             | Pixiejianfa                |
| NULL             | Jiuyinbaiguzhua       |
+--------------+--------------------+
13 rows in set (0.01 sec)

自连接:本表中不同字段间进行连接

 代码如下 复制代码

mysql> SELECT c.Name AS student,s.Name AS teacher FROM students AS c,students AS s WHERE c.TID=s.SID;
+-----------+-------------+
| student   | teacher     |
+-----------+-------------+
| GuoJing   | DingDian    |
| YangGuo   | GuoJing     |
| DingDian  | ZhangWuji   |
| HuFei     | HuangRong   |
| HuangRong | LingHuchong |
+-----------+-------------+
5 rows in set (0.02 sec)

注意:使用了别名
三、子查询:一个查询中嵌套另外一个查询
如下:在students表中查询年龄大于平均年龄的学生

 代码如下 复制代码
mysql> SELECT Name,Age FROM students WHERE Age > (SELECT AVG(Age) FROM students);
+-------------+------+
| Name           | Age    |
+-------------+------+
| DingDian      |   25 |
| HuFei           |   31 |
| Xuzhu           |   26 |
| LingHuchong |   22 |
+-------------+------+
4 rows in set (0.08 sec)

子查询注意事项:

■比较操作中使用子查询:子查询只能返回单个值;
■IN(): 使用子查询;
■在FROM中使用子查询;
联合查询:UNION,将两个查询的结果合并

 代码如下 复制代码
mysql> (SELECT Name,Age FROM students) UNION (SELECT Tname,Age FROM tutors);
+--------------+------+
| Name             | Age    |
+--------------+------+
| GuoJing          |   19   |
| YangGuo        |   17   |
| DingDian        |   25   |
| HuFei              |   31   |
| HuangRong    |   16   |
| YueLingshang |   18   |
| ZhangWuji      |   20   |
| HuYidao          |   42  |
| NingZhongze  |   49   |
+--------------+------+
19 rows in set (0.00 sec)
时间: 2024-10-27 04:02:06

MySQL基本SQL查询语句:多表查询和子查询示例的相关文章

MySQL数据库学习笔记(六)----MySQL多表查询之外键、表连接、子查询、索引

本章主要内容: 一.外键 二.表连接 三.子查询 四.索引 一.外键: 1.什么是外键 2.外键语法  3.外键的条件 4.添加外键 5.删除外键 1.什么是外键: 主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性 外键:是另一表的主键, 外键可以有重复的, 可以是空值,用来和其他表建立联系用的.所以说,如果谈到了外键,一定是至少涉及到两张表.例如下面这两张表: 上面有两张表:部门表(dept).员工表(emp).Id=Dept_id,而Dept_id就是员工表中的外键:因

Oracle数据库入门之多表连接与子查询

Oracle表连接 概述:SQL/Oracle使用表连接从多个表中查询数据 格式:select 字段列表 from table1,table2 where table1.column1=table2.column2; 说明:当被连接的多个表中存在同名字段时,必须在该字段前加上"table."作为前缀 如果没有限定where连接条件,否则就会出现笛卡尔集的不现实或没有实用意义的结果 举例:select empno, ename, sal, emp.deptno, dname, loc f

mysql多表连接和子查询

文章实例的数据表,来自上一篇博客<mysql简单查询>:http://blog.csdn.net/zuiwuyuan/article/details/39349611 MYSQL的多表连接建立在有相互关系的父子表上,分为交叉连接.内连接.外连接.自连接 一. 交叉连接/笛卡尔交集 SELECT COUNT(*) FROM emp; # 返回14行 SELECT COUNT(*) FROM dept; #返回4行 SELECT COUNT(*) FROM emp,dept; #返回14*4=56

SQL学习笔记八 索引,表连接,子查询,ROW_NUMBER

索引 经常要查询的语句,则给它建一个索引 表连接 select T_Oders as o join T_Customers as C on o.CustomerId = c.Id 子查询 单值子查询 单列多值子查询 ROW_NUMBER()函数 ROW_NUMBER() OVER(ORDER BY Fsalary DESC)

SQL学习笔记八 索引,表连接,子查询,ROW_NUMBER_MsSql

索引 经常要查询的语句,则给它建一个索引 表连接 select T_Oders as o join T_Customers as C on o.CustomerId = c.Id 子查询 单值子查询 单列多值子查询 ROW_NUMBER()函数 ROW_NUMBER() OVER(ORDER BY Fsalary DESC)

SQL循序渐进(20)Aliases 、In以及子查询

Aliases .In以及子查询 在本节教程中,我们将要介绍Aliases. In以及子查询的用法.首先我们看一下一个查询语句,它搜索所有已经定货的顾客的LastName以及他们定什么货,语句如下: SELECT OWN.OWNERLASTNAME Last Name, ORD.ITEMDESIRED Item Ordered FROM ORDERS ORD, ANTIQUEOWNERS OWN WHERE ORD.OWNERID = OWN.OWNERID AND ORD.ITEMDESIRE

sql语句实现表的字段名查询

下面为您介绍的是查询表的字段名的sql语句写法,sql语句可以实现许多的功能,希望可以您在学习sql语句使用方面获得启示. select name from syscolumns where id = (select id from sysobjects where type = 'u' and name = '相应表名')   或者   select name from syscolumns where id = object_id('相应表名')  用以上sql语句输入相应表名就可以查到表的

SQL动态拼接 如何转换为Hibernate复杂子查询?

问题描述 表结构如下表名主键名字年龄手机号用户表Useridnameagemobile客户表Custidnameagemobile主键user外键cust外键服务表ServiceiduserIdcustId//两个外键均为多对一关系根据前台要查询的四个值做SQL拼接类似于这样子select*fromservicesleftjoinuseruserons.userId=user.IdleftjoinCustcustons.custId=cust.Idwhere1=1if(userName!=nul

SQL SELECT 语句的表连接

我来给大家介绍join(连接)的概念. 为此准备了两个试验用表: album(专辑表) 和 track(曲目表). 专辑表:包含200首来自Amazon的音乐CD的概要信息. album(asin, title, artist, price, release, label, rank) 曲目表:每张专辑中的曲目(因为是音乐CD,所以也可叫歌曲)的详细信息. track(album, dsk, posn, song) SQL短语 FROM album JOIN track ON album.asi