6. Navicat pymysql 多表查询

 https://www.cnblogs.com/clschao/articles/10023248.html  Navicat 和  pymysql

https://www.cnblogs.com/clschao/articles/9995815.html#_label2 多表查询

# 昨日内容回顾

行记录的增删改查

增加

```
insert into 表名 values(1,2),(1,2);
```

删除

```
delete from 表名 where id = 1;
清空表
truncate 表名;清空表 自增重置
```

修改

```
update 表名 set 要修改的字段名称=改后的值 where id=1;
```

查询

```
select distinct 字段1 as a,字段2... from 库名.表名 (如果没有use连接到某个库,需要写上库名)
where     条件
group by   分组依据字段
having     分组后再过滤
order by   排序 order by 字段 asc,字段 desc;
limit    limit 3    limit 5,5 从索引为5的记录(第六条)开始算上这一条取5条

```

聚合函数

```
sum avg count 等等
```

# 今日内容

多表查询

​ 1.笛卡尔积:将两表所有的数据一一对应,生成一张大表

```

select * from dep,emp; #两个表拼一起
select * from dep,emp where dep.id = emp.dep_id; #找到两表之间对应的关系记录
select * from dep,emp where dep.id = emp.dep_id and dep.name='技术'; #筛选部门名称为技术的大表中的记录
select emp.name from dep,emp where dep.id = emp.dep_id and dep.name='技术'; #拿到筛选后的记录的员工姓名字段数据

```

2. 连表查询

1. inner join 内连接

```
第一步:连表
select * from dep inner join emp on dep.id=emp.dep_id;
第二步: 过滤
select * from dep inner join emp on dep.id=emp.dep_id where dep.name='技术';
第三步:找对应字段数据
select emp.name from dep inner join emp on dep.id=emp.dep_id where dep.name='技术';
```

left join 左连接(left join左边的表为主表,主表记录必须全部显示,辅表没办法对应上的,就通过null来补全)

```
select * from dep left join emp on dep.id=emp.dep_id;
```

right join 右连接

```
select * from dep right join emp on dep.id=emp.dep_id;
```

union 全连接

```
mysql> select * from dep left join emp on dep.id=emp.dep_id
-> union
-> select * from dep right join emp on dep.id=emp.dep_id;
```

子查询:(一个查询结果集作为另一个查询的条件)

```
select name from emp where dep_id = (select id from dep where name = '技术');
```

Navicat工具使用

​ 看博客

pymysql python连接mysql的客户端

```
import pymysql
conn = pymysql.connect(
host='127.0.0.1', #主机
port=3306, #端口号
user='root',#用户名
password='666', #密码
database='day43', #需要连接的库
charset='utf8'
)
cursor = conn.cursor()

sql = "select * from dep;"
ret = cursor.execute(sql) #ret 受影响的行数
print(cursor.fetchall()) #取出所有的
print(cursor.fetchmany(3)) #取出多条
print(cursor.fetchone()) #取出单条

cursor.scroll(3,'absolute') #绝对移动,按照数据最开始位置往下移动3条
cursor.scroll(3,'relative') #相对移动,按照当前光标位置往下移动3条

conn.commit() #增删改操作时,需要进行提交


sql注入:解决方案
cursor.execute(sql,[参数1,参数2...])

```

 

posted @ 2020-06-17 10:02  蜗牛般庄  阅读(214)  评论(0编辑  收藏  举报
Title
页脚 HTML 代码