使用navicat管理数据库

python与mysql(三)

python与mysql(三) python与mysql(三)

在图形界面中我们可以进行简单的增删查改

但是要使用复杂的sql语句 我们可以使用查询 在查询中写sql语句

python与mysql(三) python与mysql(三)

python与mysql(三)

CTRL+/ 注释行

  

mysql与编程结合实现 

 python与mysql(三)

将三个表连接起来

python与mysql(三)

python与mysql(三)

其他知识:

1.去重

在使用MySQL时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段,例如有如下表user:

python与mysql(三)

用distinct来返回不重复的用户名:select distinct name from user;,结果为:

python与mysql(三)

这样只把不重复的用户名查询出来了,但是用户的id,并没有被查询出来:select distinct name,id from user;,这样的结果为:

python与mysql(三)

distinct name,id 这样的mysql 会认为要过滤掉name和id两个字段都重复的记录,如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。

所以一般distinct用来查询不重复记录的条数。

如果要查询不重复的记录,有时候可以用group by :

select id,name from user group by name;

 2.临时表

首先,临时表只在当前连接可见,当关闭连接时,Mysql会自动删除表并释放所有空间。因此在不同的连接中可以创建同名的临时表,并且操作属于本连接的临时表。

        创建临时表的语法与创建表语法类似,不同之处是增加关键字TEMPORARY,如:

               CREATE TEMPORARY TABLE 表名 (…. )

 

       临时表使用有一些限制条件

  *  临时表在 memory、myisam、merge或者innodb上使用,并且不支持mysql cluster簇);

               show tables语句不会列出临时表,在information_schema中也不存在临时表信息;show create table可以查看临时表;

  *  不能使用rename来重命名临时表。但是可以alter table rename代替:

             mysql>ALTER TABLE orig_name RENAME new_name;

  *  可以复制临时表得到一个新的临时表,如:

                mysql>create temporary table new_table select * from old_table;

  *  但在同一个query语句中,相同的临时表只能出现一次。如:

               可以使用:mysql> select * from temp_tb;

               但不能使用:mysql> select * from temp_tb, temp_tb as t;

               错误信息:   ERROR 1137 (HY000): Can't reopen table: 'temp_tb'

        同样相同临时表不能在存储函数中出现多次,如果在一个存储函数里,用不同的别名查找一个临时表多次,或者在这个存储函数里用不同的语句查找,都会出现这个错误。

  *  但不同的临时表可以出现在同一个query语句中,如临时表temp_tb1, temp_tb2:

                 Mysql> select * from temp_tb1, temp_tb2;

        临时表可以手动删除:

                 DROP TEMPORARY TABLE IF EXISTS temp_tb;

 

       临时表主要用于对大数据量的表上作一个子集,提高查询效率

 

       在创建临时表时声明类型为HEAP,则Mysql会在内存中创建该临时表,即内存表:如:

                CREATE TEMPORARY TABLE 表名 (。。。。) TYPE = HEAP

       因为HEAP表存储在内存中,你对它运行的查询可能比磁盘上的临时表快些。如:

mysql> create temporary table temp_tb type='heap' select * from temptb;

Query OK, 0 rows affected, 1 warning (0.01 sec)

Records: 0  Duplicates: 0  Warnings: 0

 

mysql> show create table temp_tb \G;

*************************** 1. row ***************************

       Table: temp_tb

Create Table: CREATE TEMPORARY TABLE `temp_tb` (

  `id` int(10) unsigned NOT NULL DEFAULT '0',

  `Name` char(20) NOT NULL,

  `Age` tinyint(4) NOT NULL

) ENGINE=MEMORY DEFAULT CHARSET=gbk

1 row in set (0.00 sec)

 

ERROR:

No query specified

         可以看出来临时表和内存表的ENGINE 不同,临时表默认的是Mysql指定的默认Engine,而内存表是MEMORY

官方手册:
As indicated by the name, MEMORY tables are stored in memory. They use hash indexes by default, which makes them very fast, and very useful for creating temporary tables. However, when the server shuts down, all rows stored in MEMORY tables are lost. The tables themselves continue to exist because their definitions are stored in .frm files on disk, but they are empty when the server restarts.

 

内存表的建立还有一些限制条件
      MEMORY tables cannot contain        BLOB or TEXT columns. HEAP不支持BLOB/TEXT列。    
      The server needs sufficient memory to maintain all   MEMORY tables that are in use at the same time. 在同一时间需要足够的内存.
      To free memory used by a MEMORY table when   you no longer require its contents, you should execute DELETE or TRUNCATE TABLE, or remove the table altogether using DROP        TABLE.为了释放内存,你应该执行DELETE FROM heap_table或DROP TABLE heap_table。

 

临时表和内存表

        临时表主要是为了放一些中间大结果集的一些子集,内存表可以放一些经常频繁使用的数据。

        *  临时表:表建在内存里,数据在内存里
        *  内存表:表建在磁盘里,数据在内存里

        临时表和内存表所使用内存大小可以通过My.cnf中的max_heap_table_size、tmp_table_size指定:
              [mysqld]
              max_heap_table_size=1024M   #内存表容量
              tmp_table_size=1024M              #临时表容量

        当数据超过临时表的最大值设定时,自动转为磁盘表,此时因需要进行IO操作,性能会大大下降,而内存表不会,内存表满后,则会提示数据满错误。

       show tables 命令不会显示临时表。

        以下是对内存表和临时表之间区别的总结:

   内存表:

        1.缺省存储引擎为MEMORY
        2.可以通过参数max_heap_table_size来设定内存表大小
        3.到达max_heap_table_size设定的内存上限后将报错
        4.表定义保存在磁盘上,数据和索引保存在内存中
        5.不能包含TEXT、BLOB等字段
   临时表:

        1.缺省存储引擎为MySQL服务器默认引擎,引擎类型只能是:memory(heap)、myisam、merge、innodb(memory临时表由于表的增大可能会转变为myisam临时表)
        2.可以通过参数 tmp_table_size 来设定临时表大小。
        3.到达tmp_table_size设定的内存上限后将在磁盘上创建临时文件
        4.表定义和数据都保存在内存中
        5.可以包含TEXT, BLOB等字段

        临时表一般比较少用,通常是在应用程序中动态创建或者由MySQL内部根据SQL执行计划需要自己创建。

        内存表则大多作为Cache来使用,特别在没有第三方cache使用时。如今随着memcache、NoSQL的流行,越来越少选择使用内存表。

 

MySQL服务器使用内部临时表

        在某些情况下,mysql服务器会自动创建内部临时表。查看查询语句的执行计划,如果extra列显示“using temporary”即使用了内部临时表。内部临时表的创建条件:

        *  group by 和 order by中的列不相同

        *  order by的列不是引用from 表列表中 的第一表

        *  group by的列不是引用from 表列表中 的第一表

        *  使用了sql_small_result选项

        *  含有distinct 的 order by语句

        初始创建内部myisam临时表的条件:

        *  表中存在text、blob列

        *  在group by中的 列 有超过512字节

        *  在distinct查询中的 列 有超过512字节

        *  在union、union all联合查询中,select 列 列表中的 列 有超过512字节的

3.avg 求平均值

MySQL AVG()函数简介

MySQL AVG()函数是一个聚合函数,它用于计算一组值或表达式的平均值。

AVG()函数的语法如下:

AVG(DISTINCT expression)

SQL

您可以使用AVG()函数中的DISTINCT运算符来计算不同值的平均值。 例如,如果您有一组值1,1,2,3,具有DISTINCT操作的AVG()函数将返回不同值的和,即:(1 + 2 + 3)/3 = 2.00

MySQL AVG示例

我们将在示例数据库(yiibaidb)中使用products表进行演示,下图是products表的结构 -

mysql> desc products;
+--------------------+---------------+------+-----+---------+------------------+
| Field              | Type          | Null | Key | Default | Extra            |
+--------------------+---------------+------+-----+---------+------------------+
| productCode        | varchar(15)   | NO   | PRI |         |                  |
| productName        | varchar(70)   | NO   | MUL | NULL    |                  |
| productLine        | varchar(50)   | NO   | MUL | NULL    |                  |
| productScale       | varchar(10)   | NO   |     | NULL    |                  |
| productVendor      | varchar(50)   | NO   |     | NULL    |                  |
| productDescription | text          | NO   |     | NULL    |                  |
| quantityInStock    | smallint(6)   | NO   |     | NULL    |                  |
| buyPrice           | decimal(10,2) | NO   |     | NULL    |                  |
| MSRP               | decimal(10,2) | NO   |     | NULL    |                  |
| stockValue         | double        | YES  |     | NULL    | STORED GENERATED |
+--------------------+---------------+------+-----+---------+------------------+
10 rows in set

SQL

要计算products表中所有产品的平均价格,可以使用AVG函数,如下查询:

SELECT AVG(buyprice) 'Avarage Price' FROM products;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT AVG(buyprice) 'Avarage Price' FROM products;
+---------------+
| Avarage Price |
+---------------+
| 54.395182     |
+---------------+
1 row in set

SQL

请注意,FORMAT函数用于格式化AVG函数返回的平均值。

您可以向SELECT语句添加一个WHERE子句来计算子集值的平均值。 例如,要计算产品线为Classic Cars的产品的平均价格,您可以使用以下查询:

SELECT AVG(buyprice) 'Avarage Classic Cars Price'
FROM products
WHERE productline = 'Classic Cars';

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT AVG(buyprice) 'Avarage Classic Cars Price'
FROM products
WHERE productline = 'Classic Cars';
+----------------------------+
| Avarage Classic Cars Price |
+----------------------------+
| 64.446316                  |
+----------------------------+
1 row in set

SQL

具有DISTINCT的MySQL AVG()函数

有些产品价格相同,可以使用以下查询来检查它:

SELECT COUNT(buyprice) - COUNT(DISTINCT buyprice) FROM products;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT COUNT(buyprice) - COUNT(DISTINCT buyprice) FROM products;
+--------------------------------------------+
| COUNT(buyprice) - COUNT(DISTINCT buyprice) |
+--------------------------------------------+
|                                          2 |
+--------------------------------------------+
1 row in set

SQL

可以使用AVG()函数通过添加DISTINCT运算符来计算不同价格的平均值,如下所示:

SELECT AVG(DISTINCT buyprice) FROM products;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT AVG(DISTINCT buyprice) FROM products;
+------------------------+
| AVG(DISTINCT buyprice) |
+------------------------+
| 54.372870              |
+------------------------+
1 row in set

SQL

结果与使用DISTINCT操作符的平均价格略有不同。

具有GROUP BY子句的MySQL AVG

我们经常使用AVG函数与GROUP BY子句一起计算表中每组行的平均值。

例如,要计算每个产品线的产品的平均价格,您将使用带有GROUP BY子句的AVG函数,如下查询语句:

SELECT productline,
       AVG(buyprice) 'Avarage Price'
FROM products
GROUP BY productline;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT productline,
       AVG(buyprice) 'Avarage Price'
FROM products
GROUP BY productline;
+------------------+---------------+
| productline      | Avarage Price |
+------------------+---------------+
| Classic Cars     | 64.446316     |
| Motorcycles      | 50.685385     |
| Planes           | 49.629167     |
| Ships            | 47.007778     |
| Trains           | 43.923333     |
| Trucks and Buses | 56.329091     |
| Vintage Cars     | 46.066250     |
+------------------+---------------+
7 rows in set

SQL

具有HAVING子句的MySQL AVG

您可以使用AVG函数中的HAVING子句中为分组的平均值设置条件。 例如,如果要仅选择产品平均价格大于50的产品线,则可以使用以下查询:

SELECT productline, AVG(buyprice) 'Avarage Price' FROM products GROUP BY productline HAVING AVG(buyprice) > 50;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT productline, AVG(buyprice) 'Avarage Price' FROM products GROUP BY productline HAVING AVG(buyprice) > 50;
+------------------+---------------+
| productline      | Avarage Price |
+------------------+---------------+
| Classic Cars     | 64.446316     |
| Motorcycles      | 50.685385     |
| Trucks and Buses | 56.329091     |
+------------------+---------------+
3 rows in set

SQL

MySQL AVG()函数与子查询

您可以在SQL语句中多次使用AVG()函数来计算一组平均值的平均值。 例如,可以计算产品线平均购买价格的平均买价如下:

SELECT AVG(pl_avg) 'Average Product'
FROM (
    SELECT AVG(buyprice) pl_avg
    FROM products
    GROUP BY productline
) avgs;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT AVG(pl_avg) 'Average Product'
FROM (
    SELECT AVG(buyprice) pl_avg
    FROM products
    GROUP BY productline
) avgs;
+-----------------+
| Average Product |
+-----------------+
| 51.1553314286   |
+-----------------+
1 row in set

Shell

怎么运行的 -

  • 子查询根据产品线计算平均购买价格。
  • 外部查询计算从子查询返回的产品线的平均购买价格的平均购买价格。

具有NULL值的MySQL AVG函数

AVG()函数忽略计算中的NULL值,请参阅以下示例:

首先,创建一个名为t的新表,其中有两列idvalval列可以包含NULL值。

CREATE TABLE IF NOT EXISTS t(
    id  int auto_increment primary key,
    val int
);

SQL

其次,在t表中插入一些行,包括NULL值。

INSERT INTO t(val)
VALUES(1),(2),(nulL),(3);

SQL

第三,使用AVG()函数计算val列中值的平均值:

SELECT AVG(val) FROM t;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT AVG(val) FROM t;
+----------+
| AVG(val) |
+----------+
| 2.0000   |
+----------+
1 row in set

SQL

该语句按预期返回2,因为在AVG函数的计算中不包括NULL值。

具有控制流函数的MySQL AVG

要计算列的平均值,并在单个语句中有条件地计算相同列的平均值,可以使用具有控制流函数(如IFCASEIFNULLNULLIF等)的AVG函数。

例如,要计算Classic Cars产品线的平均价格与所有产品的平均价格的比例,请使用以下声明:

SELECT AVG(IF(productline='Classic Cars',buyprice,NULL)) / AVG(buyprice) 'Classic Cars/ Products'
FROM products;

SQL

执行上面查询语句,得到以下结果 -

mysql> SELECT AVG(IF(productline='Classic Cars',buyprice,NULL)) / AVG(buyprice) 'Classic Cars/ Products'
FROM products;
+------------------------+
| Classic Cars/ Products |
+------------------------+
| 1.1847798580           |
+------------------------+
1 row in set

SQL

如果产品线是Classic Cars,则IF(productline='Classic Cars',buyprice,NULL)表达式返回价格,否则返回NULL

因为AVG函数忽略了计算中的NULL值,所以AVG(IF(productline ='Classic Cars',buyprice,NULL))表达式只计算产品线是Classic Cars的产品的平均价格。

在本教程中,我们向您展示了一些有用的技术,通过使用MySQL AVG函数来计算一组值的平均值。

原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/mysql/avg.html
 

 

 

数据 结构的导出

导出现有数据库数据:

  • mysqldump -u用户名 -p密码 数据库名称 >导出文件路径           # 结构+数据
  • mysqldump -u用户名 -p密码 -d 数据库名称 >导出文件路径       # 结构 

导入现有数据库数据:

  • mysqldump -uroot -p密码  数据库名称 < 文件路径

 

或者在navicat中视图操作

python与mysql(三)

 导出后会自动生成同样结构(数据)的数据库 的sql语句

eg:

 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50624
 Source Host           : localhost
 Source Database       : sqlexam

 Target Server Type    : MySQL
 Target Server Version : 50624
 File Encoding         : utf-8

 Date: 10/21/2016 06:46:46 AM
*/

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `class`
-- ----------------------------
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `caption` varchar(32) NOT NULL,
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `class`
-- ----------------------------
BEGIN;
INSERT INTO `class` VALUES ('1', '三年二班'), ('2', '三年三班'), ('3', '一年二班'), ('4', '二年九班');
COMMIT;

-- ----------------------------
--  Table structure for `course`
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `cname` varchar(32) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  PRIMARY KEY (`cid`),
  KEY `fk_course_teacher` (`teacher_id`),
  CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `course`
-- ----------------------------
BEGIN;
INSERT INTO `course` VALUES ('1', '生物', '1'), ('2', '物理', '2'), ('3', '体育', '3'), ('4', '美术', '2');
COMMIT;

-- ----------------------------
--  Table structure for `score`
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `course_id` int(11) NOT NULL,
  `num` int(11) NOT NULL,
  PRIMARY KEY (`sid`),
  KEY `fk_score_student` (`student_id`),
  KEY `fk_score_course` (`course_id`),
  CONSTRAINT `fk_score_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`cid`),
  CONSTRAINT `fk_score_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `score`
-- ----------------------------
BEGIN;
INSERT INTO `score` VALUES ('1', '1', '1', '10'), ('2', '1', '2', '9'), ('5', '1', '4', '66'), ('6', '2', '1', '8'), ('8', '2', '3', '68'), ('9', '2', '4', '99'), ('10', '3', '1', '77'), ('11', '3', '2', '66'), ('12', '3', '3', '87'), ('13', '3', '4', '99'), ('14', '4', '1', '79'), ('15', '4', '2', '11'), ('16', '4', '3', '67'), ('17', '4', '4', '100'), ('18', '5', '1', '79'), ('19', '5', '2', '11'), ('20', '5', '3', '67'), ('21', '5', '4', '100'), ('22', '6', '1', '9'), ('23', '6', '2', '100'), ('24', '6', '3', '67'), ('25', '6', '4', '100'), ('26', '7', '1', '9'), ('27', '7', '2', '100'), ('28', '7', '3', '67'), ('29', '7', '4', '88'), ('30', '8', '1', '9'), ('31', '8', '2', '100'), ('32', '8', '3', '67'), ('33', '8', '4', '88'), ('34', '9', '1', '91'), ('35', '9', '2', '88'), ('36', '9', '3', '67'), ('37', '9', '4', '22'), ('38', '10', '1', '90'), ('39', '10', '2', '77'), ('40', '10', '3', '43'), ('41', '10', '4', '87'), ('42', '11', '1', '90'), ('43', '11', '2', '77'), ('44', '11', '3', '43'), ('45', '11', '4', '87'), ('46', '12', '1', '90'), ('47', '12', '2', '77'), ('48', '12', '3', '43'), ('49', '12', '4', '87'), ('52', '13', '3', '87');
COMMIT;

-- ----------------------------
--  Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `gender` char(1) NOT NULL,
  `class_id` int(11) NOT NULL,
  `sname` varchar(32) NOT NULL,
  PRIMARY KEY (`sid`),
  KEY `fk_class` (`class_id`),
  CONSTRAINT `fk_class` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `student`
-- ----------------------------
BEGIN;
INSERT INTO `student` VALUES ('1', '男', '1', '理解'), ('2', '女', '1', '钢蛋'), ('3', '男', '1', '张三'), ('4', '男', '1', '张一'), ('5', '女', '1', '张二'), ('6', '男', '1', '张四'), ('7', '女', '2', '铁锤'), ('8', '男', '2', '李三'), ('9', '男', '2', '李一'), ('10', '女', '2', '李二'), ('11', '男', '2', '李四'), ('12', '女', '3', '如花'), ('13', '男', '3', '刘三'), ('14', '男', '3', '刘一'), ('15', '女', '3', '刘二'), ('16', '男', '3', '刘四');
COMMIT;

-- ----------------------------
--  Table structure for `teacher`
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `tid` int(11) NOT NULL AUTO_INCREMENT,
  `tname` varchar(32) NOT NULL,
  PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `teacher`
-- ----------------------------
BEGIN;
INSERT INTO `teacher` VALUES ('1', '张磊老师'), ('2', '李平老师'), ('3', '刘海燕老师'), ('4', '朱云海老师'), ('5', '李杰老师');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

 

相关文章:

  • 2021-06-03
  • 2021-07-26
  • 2022-12-23
  • 2022-03-06
  • 2022-12-23
  • 2021-11-25
  • 2021-07-10
  • 2021-04-18
猜你喜欢
  • 2022-01-30
  • 2021-05-15
  • 2021-11-03
  • 2021-11-19
  • 2021-08-12
  • 2022-12-23
  • 2021-10-06
相关资源
相似解决方案