python 之 数据库(多表查询之连接查询、子查询、pymysql模块的使用)

10.10 多表连接查询

10.101 内连接

把两张表有对应关系的记录连接成一张虚拟表

select * from emp,dep;                                  #连接两张表的笛卡尔积
select * from emp,dep where emp.dep_id = dep.id;            # 不推荐用where连接表
select * from emp inner join dep on emp.dep_id = dep.id;    #推荐
+----+-----------+--------+------+--------+------+--------------+
| id | name      | sex    | age  | dep_id | id   | name         |
+----+-----------+--------+------+--------+------+--------------+
|  1 | egon      | male   |   18 |    200 |  200 | 技术         |
|  2 | alex      | female |   48 |    201 |  201 | 人力资源     |
|  3 | wupeiqi   | male   |   38 |    201 |  201 | 人力资源     |
|  4 | yuanhao   | female |   28 |    202 |  202 | 销售         |
|  5 | liwenzhou | male   |   18 |    200 |  200 | 技术         |
+----+-----------+--------+------+--------+------+--------------+

#应用:
select * from emp,dep where emp.dep_id = dep.id and dep.name = "技术";
select * from emp inner join dep on emp.dep_id = dep.id where dep.name = "技术";
+----+-----------+------+------+--------+------+--------+
| id | name      | sex  | age  | dep_id | id   | name   |
+----+-----------+------+------+--------+------+--------+
|  1 | egon      | male |   18 |    200 |  200 | 技术   |
|  5 | liwenzhou | male |   18 |    200 |  200 | 技术   |
+----+-----------+------+------+--------+------+--------+

应用

10.102 左连接

在内连接的基础上,保留左边没有对应关系的记录

select * from emp left join dep on emp.dep_id = dep.id;
+----+------------+--------+------+--------+------+--------------+
| id | name       | sex    | age  | dep_id | id   | name         |
+----+------------+--------+------+--------+------+--------------+
|  1 | egon       | male   |   18 |    200 |  200 | 技术         |
|  5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
|  2 | alex       | female |   48 |    201 |  201 | 人力资源     |
|  3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
|  4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
|  6 | jingliyang | female |   18 |    204 | NULL | NULL         |
+----+------------+--------+------+--------+------+--------------+

10.103 右连接

在内连接的基础上,保留右边没有对应关系的记录

select * from emp right join dep on emp.dep_id = dep.id;
+------+-----------+--------+------+--------+------+--------------+
| id   | name      | sex    | age  | dep_id | id   | name         |
+------+-----------+--------+------+--------+------+--------------+
|    1 | egon      | male   |   18 |    200 |  200 | 技术         |
|    2 | alex      | female |   48 |    201 |  201 | 人力资源     |
|    3 | wupeiqi   | male   |   38 |    201 |  201 | 人力资源     |
|    4 | yuanhao   | female |   28 |    202 |  202 | 销售         |
|    5 | liwenzhou | male   |   18 |    200 |  200 | 技术         |
| NULL | NULL      | NULL   | NULL |   NULL |  203 | 运营         |
+------+-----------+--------+------+--------+------+--------------+

10.104 全连接

在内连接的基础上,保留左、右边没有对应关系的记录,并去重

select * from emp left join dep on emp.dep_id = dep.id
union
select * from emp right join dep on emp.dep_id = dep.id;
+------+------------+--------+------+--------+------+--------------+
| id   | name       | sex    | age  | dep_id | id   | name         |
+------+------------+--------+------+--------+------+--------------+
|    1 | egon       | male   |   18 |    200 |  200 | 技术         |
|    5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
|    2 | alex       | female |   48 |    201 |  201 | 人力资源     |
|    3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
|    4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
|    6 | jingliyang | female |   18 |    204 | NULL | NULL         |
| NULL | NULL       | NULL   | NULL |   NULL |  203 | 运营         |
+------+------------+--------+------+--------+------+--------------+

补充:多表连接可以不断地与虚拟表连接

#查找各部门最高工资
select t1.* from emp as t1 inner join (select post,max(salary) as ms from emp group by post) as t2
on t1.post = t2.post
where t1.salary = t2.ms;

10.11 子查询

把一个查询语句用括号括起来,当做另外一条查询语句的条件去用,称为子查询

#查询技术部员工的名字
select emp.name from emp inner join dep on emp.dep_id = dep.id where dep.name="技术";#连接查询
select name from emp where dep_id =(select id from dep where name="技术");          #子查询
+-----------+
| name      |
+-----------+
| egon      |
| liwenzhou |
+-----------+
#查询平均年龄在25岁以上的部门名                                                       #子查询
select name from dep where id in (select dep_id from emp group by dep_id having avg(age) > 25);
select dep.name from emp inner join dep on emp.dep_id = dep.id                         #连接查询
    group by dep.name
    having avg(age) > 25;
+--------------+
| name         |
+--------------+
| 人力资源      |
| 销售          |
+--------------+
#查询每个部门最新入职的那位员工
select t1.id,t1.name,t1.post,t1.hire_date,t2.post,t2.max_date from (emp as t1) inner join
(select post,max(hire_date) as max_date from emp group by post) as t2   #拿到最大雇佣时间
on t1.post = t2.post
where t1.hire_date = t2.max_date;
+----+--------+-----------------------------------------+----
| id | name   | post    | hire_date  | post    |  max_date  |
+----+--------+-----------------------------------------+-----
|  1 | egon   | 外交大使 | 2017-03-01 | 外交大使 | 2017-03-01 |
|  2 | alex   | teacher | 2015-03-02 | teacher  | 2015-03-02 |
| 13 | 格格   | sale     | 2017-01-27 | sale     | 2017-01-27 |
| 14 | 张野   | operation| 2016-03-11 | operation| 2016-03-11 |
+----+--------+-----------------------------------------+-----

exists( ):括号内的值存在时满足条件

select * from emp where exists (select id from dep where id > 3);       #找到所有

10.12 pymysql模块的使用

10.121 pymysql查

import pymysql              #pip3 install pymysql
conn=pymysql.connect(        #连接
    host=‘127.0.0.1‘,
    port=3306,
    user=‘root‘,
    password=‘‘,
    database=‘db2‘,
    charset=‘utf8‘)
cursor=conn.cursor(pymysql.cursors.DictCursor)#以字典形式显示表的记录
rows=cursor.execute(‘show tables;‘)           #1 显示受影响的行数(row),此处为有表的条数
print(rows)
rows=cursor.execute(‘select * from emp;‘)      #18 此处rows为emp表内有记录的条数
print(rows)
?
print(cursor.fetchone())     #查看一条记录 一个字典{key:value}
print(cursor.fetchmany(2))   #查看多条记录 [{key:value},]
#print(cursor.fetchall())    #查看所有记录 强调:下一次查找是接着上一次查找的位置继续
?
cursor.scroll(0,‘absolute‘)  #绝对移动,以0位置为参照显示
print(cursor.fetchone())
?
cursor.scroll(1,‘relative‘)  #相对移动,相对当前位置移动1条记录
print(cursor.fetchone())
?
cursor.close()#光标
conn.close()

10.122 防止sql注入问题

在服务端防止sql注入问题:不要自己拼接字符串,让pymysql模块去拼接,pymysql拼接时会过滤非法字符

import pymysql
conn=pymysql.connect(
    host=‘127.0.0.1‘,
    port=3306,
    user=‘root‘,
    password=‘‘,
    database=‘db2‘,
    charset=‘utf8‘
)
cursor=conn.cursor(pymysql.cursors.DictCursor)
?
inp_user=input(‘用户名>>:‘).strip() #inp_user=""
inp_pwd=input(‘密码>>:‘).strip() #inp_pwd=""
sql="select * from user where username=%s and password=%s"
print(sql)

rows=cursor.execute(sql,(inp_user,inp_pwd))#输入的用户名和密码中的非法字符会被过滤掉
if rows:
    print(‘登录成功‘)
else:
    print(‘登录失败‘)
cursor.close()
conn.close()

10.123 pymysql增删改

import pymysql
conn=pymysql.connect(
    host=‘127.0.0.1‘,
    port=3306,
    user=‘root‘,
    password=‘‘,
    database=‘db2‘,
    charset=‘utf8‘)
cursor=conn.cursor(pymysql.cursors.DictCursor)
sql=‘insert into user(username,password) values(%s,%s)‘         #插入单行记录
rows=cursor.execute(sql,(‘EGON‘,‘123456‘))
print(rows)
print(cursor.lastrowid)                                      #显示当前最后一行的id
?
sql=‘insert into user(username,password) values(%s,%s)‘         #一次插入多行记录
rows=cursor.executemany(sql,[(‘lwz‘,‘123‘),(‘evia‘,‘455‘),(‘lsd‘,‘333‘)])
print(rows)
?
rows=cursor.execute(‘update user set username="alexSB" where id=2‘)#修改记录
print(rows)
?
conn.commit() # 只有commit提交才会完成真正的修改
cursor.close()
conn.close()

原文地址:https://www.cnblogs.com/mylu/p/11305700.html

时间: 2024-08-30 03:16:37

python 之 数据库(多表查询之连接查询、子查询、pymysql模块的使用)的相关文章

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

注:本文转自:http://www.cnblogs.com/smyhvae/p/4042303.html 本章主要内容: 一.外键 二.表连接 三.子查询 四.索引 一.外键: 1.什么是外键 2.外键语法 3.外键的条件 4.添加外键 5.删除外键 1.什么是外键: 主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性 外键:是另一表的主键, 外键可以有重复的, 可以是空值,用来和其他表建立联系用的.所以说,如果谈到了外键,一定是至少涉及到两张表.例如下面这两张表: 上面有两

MySQL多表查询之外键、表连接、子查询、索引

一.外键: 1.什么是外键 2.外键语法 3.外键的条件 4.添加外键 5.删除外键 1.什么是外键: 主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性 外键:是另一表的主键, 外键可以有重复的, 可以是空值,用来和其他表建立联系用的.所以说,如果谈到了外键,一定是至少涉及到两张表.例如下面这两张表: 上面有两张表:部门表(dept).员工表(emp).Id=Dept_id,而Dept_id就是员工表中的外键:因为员工表中的员工需要知道自己属于哪个部门,就可以通过外键Dep

sql的基础语句-单行函数,dual,数字函数,日期函数,表连接,集合运算,分组报表,单行子查询,多行子查询

3. 单行函数 3.1 转换函数 select ascii('A'),chr(65) from dual; select to_char(1243123),1231451 from dual;靠左边的就是字符串,靠右边的就是数字 select to_char(123512a121) from dual;   --错误的写法,没有引号表示数字,但是数字里面包含了字母,不合法的输入值 select to_number('123141211') from dual; select to_number(

[Z]T-SQL查询进阶--深入理解子查询

原文链接: http://www.cnblogs.com/CareySon/archive/2011/07/18/2109406.html 引言 SQL有着非常强大且灵活的查询方式,而多表连接操作往往也可以用子查询进行替代,本篇文章将会讲述子查询的方方面面. 简介 子查询本质上是嵌套进其他SELECT,UPDATE,INSERT,DELETE语句的一个被限制的SELECT语句,在子查询中,只有下面几个子句可以使用 SELECT子句(必须) FROM子句(必选) WHERE子句(可选) GROUP

1.子查询知识体系,单行子查询,多行子查询

 1查询工资比scott高的员工信息 A 第一步:查询出scott这个员工的工资 select sal from emp where ename = 'SCOTT'; B 第二步:查询出工资比scott高的员工信息 select * fromemp where sal >3000; 总结: 子查询的本质:多个select语句的嵌套 2:子查询的知识体系搭建 A 合理的书写风格 B 子查询外面()不要忘记 C 子查询和主查询可以查询的是同一张表,也可以不是同一张表 只要子查询返回的结果,主查询

Entity Framework查询生成大量的子查询,如何避免?求救

最近使用Entity Framework做一个中型的项目,一张表含有千万条数据,并没有使用很复杂的查询,只是程序上使用了DTO进行帅选数据,且使用了分页,效果很不理想.经过跟踪sql,我发现很多简单的查询,都存在子查询,而子查询往往会影响到查询性能,在这里,我想问问大虾,除了自己写SQL语句,有没有更好的解决办法在Entity Framework基础上处理这个问题? 如图所示: Entity Framework查询代码 private async Task<QuotationDto[]> Ge

python操作数据库-数据表

数据表: 数据类型: 帮助的三种形式: 在cmd中输入: help 要帮助的主题词,或 ? 要帮助的主题词 或  \h 要帮助的主题词 . 数据表的创建: CREATE database IF NOT exists zbltest2 default character set 'utf8'; USE zbltest2; CREATE TABLE IF NOT EXISTS `user`( id SMALLINT, username VARCHAR(20) ) ENGINE=INNODB CHAR

mysql表连接,子查询以及if判断

创建表: CREATE TABLE emp ( ename varchar(10) DEFAULT NULL, hiredate date DEFAULT NULL, sal decimal(10,2) DEFAULT NULL, deptno int(2) DEFAULT NULL, age int(3) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CREATE TABLE dept ( deptno int(2) DEFAULT NUL

ORACLE 多表连接与子查询

Oracle表连接 SQL/Oracle使用表连接从多个表中查询数据 语法格式: select 字段列表from table1,table2where table1.column1=table2.column2; 说明: 在where子句中指定连接条件 当被连接的多个表中存在同名字段时,必须在该字段前加上"表名"作为前缀. 连接的类型 Oracle8i之前的表连接: 等值连接(Equijoin) 非等值连接(Non-Equijoin) 外连接(Outer join):-->左外连

关系型数据库进阶(三)连接运算及查询实例

上篇文字,我们知道如何获取数据了,那现在就把它们联接起来! 我要展现的是3个个常用联接运算符:合并联接(Merge join),哈希联接(Hash Join)和嵌套循环联接(Nested Loop Join).但是在此之前,我需要引入新词汇了:内关系和外关系(inner relation and outer relation). 一个关系可以是: 一个表 一个索引 上一个运算的中间结果(比如上一个联接运算的结果). 当你联接两个关系时,联接算法对两个关系的处理是不同的.在本文剩余部分,我将假定: