码迷,mamicode.com
首页 > 数据库 > 详细

mysql_07_连接查询

时间:2017-07-27 01:04:33      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:插入   3.3   3.2   eid   price   inno   思想   utf8   typeid   

#创建数据库
CREATE DATABASE db_book;

#使用数据库
USE `db_book`;

#表如果存在则删除
DROP TABLE IF EXISTS `t_book`;

#创建表
CREATE TABLE `t_book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bookName` varchar(20) DEFAULT NULL,
`price` decimal(6,2) DEFAULT NULL,
`author` varchar(20) DEFAULT NULL,
`bookTypeId` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

#插入数据
insert into `t_book`(`id`,`bookName`,`price`,`author`,`bookTypeId`) values (1,‘Java编程思想‘,‘100.00‘,‘埃史尔‘,1),(2,‘Java从入门到精通‘,‘80.00‘,‘李钟尉‘,1),(3,‘三剑客‘,‘70.00‘,‘大仲马‘,2),(4,‘生理学(第二版)‘,‘24.00‘,‘刘先国‘,4);

#表如果存在则删除
DROP TABLE IF EXISTS `t_booktype`;

#创建表
CREATE TABLE `t_booktype` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bookTypeName` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

#插入数据
insert into `t_booktype`(`id`,`bookTypeName`) values (1,‘计算机类‘),(2,‘文学类‘),(3,‘教育类‘);

 

#第三节:连接查询
#连接查询是将两个或两个以上的表按照某个条件连接起来,从中选取需要的数据;
#笛卡尔乘积
SELECT * FROM t_book,t_booktype;

#3.1内连接查询
#内连接查询是一种最常见的连接查询,内连接查询可以查询两个或者两个以上的表。
SELECT * FROM t_book,t_booktype WHERE t_book.bookTypeId=t_booktype.id;
SELECT bookName,author,bookTypeName FROM t_book,t_booktype WHERE t_book.bookTypeId=t_booktype.id;
SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book AS tb,t_booktype AS tby WHERE tb.bookTypeId=tby.id;

#3.2:外连接查询
#外连接查询可以查出某一张表的所有信息
#3.2.1:左连接查询
#可以查询出"表名1"的所有记录。而"表名2"中,只能查询出匹配的记录;
#SELECT 属性名列表 FROM 表名1 LEFT JOIN 表名2 ON 表名1.属性名1=表名2.属性名2;
SELECT * FROM t_book AS tb LEFT JOIN t_bookType AS tby ON tb.bookTypeId=tby.id;
SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book AS tb LEFT JOIN t_bookType AS tby ON tb.bookTypeId=tby.id;

#3.2.1:左连接查询
#可以查询出"表名2"的所有记录。而"表名1"中,只能查询出匹配的记录;
#SELECT 属性名列表 FROM 表名1 RIGHT JOIN 表名2 ON 表名1.属性名1=表名2.属性名2;
SELECT * FROM t_book AS tb RIGHT JOIN t_bookType AS tby ON tb.bookTypeId=tby.id;
SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book AS tb RIGHT JOIN t_bookType AS tby ON tb.bookTypeId=tby.id;

#3.3:多条件查询
SELECT tb.bookName,tb.author,tby.bookTypeName,tb.price FROM t_book AS tb,t_booktype AS tby WHERE tb.bookTypeId=tby.id AND tb.price>75;
SELECT tb.bookName,tb.author,tby.bookTypeName,tb.price FROM t_book AS tb,t_booktype AS tby WHERE tb.bookTypeId=tby.id AND tb.price>75 AND tb.author="埃史尔";

mysql_07_连接查询

标签:插入   3.3   3.2   eid   price   inno   思想   utf8   typeid   

原文地址:http://www.cnblogs.com/xinwenpiaoxue/p/7242513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!