当前位置: 首页 > news >正文

板凳-------Mysql cookbook学习 (九--3)

4.3 使用临时表
Drop table 语句来删除表,
选择使用create temporary table 语句,创建的是一张临时表。
Create temporary table tb1_name(…列定义…)
克隆表
Create temporary table new_table like original_table
根据查询结果建表
Create temporary table tb1_name select …
临时表可以使用普通表的表名。在临时表的生命周期内,它将屏蔽与之同名的普通表。对其任意操作,不影响真实数据。

mysql> create temporary table mail select * from mail;
Query OK, 16 rows affected (0.02 sec)
Records: 16  Duplicates: 0  Warnings: 0mysql> select count(*) from mail;
+----------+
| count(*) |
+----------+
|       16 |
+----------+
1 row in set (0.01 sec)mysql> delete from mail;
Query OK, 16 rows affected (0.00 sec)mysql> select count(*) from mail;
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)mysql> drop table mail;
Query OK, 0 rows affected (0.00 sec)mysql> select count(*) from mail;
+----------+
| count(*) |
+----------+
|       16 |
+----------+
1 row in set (0.00 sec)

只有在最后一次使用之后,数据库才会自动删除临时表
应用程序中使用一个与普通表同名的临时表时, 应用程序只会对该临时表就行修改。
应用程序API提供数据库的持久连接或者连接池, 可以使用这些技术保证临时表的持久性。
比较明智的做法是在创建临时表之前执行下面的语句
Drop temporary table if exists tb1_name

4.4 检查或改变某个表的存储引擎

mysql> SELECT engine FROM information_schema.tables-> WHERE table_schema = 'cookbook' AND table_name = 'mail';
+--------+
| ENGINE |
+--------+
| InnoDB |
+--------+
1 row in set (0.02 sec)
mysql> show table status like 'mail'\G
*************************** 1. row ***************************Name: mailEngine: InnoDBVersion: 10Row_format: DynamicRows: 16Avg_row_length: 1024Data_length: 16384
Max_data_length: 0Index_length: 16384Data_free: 0Auto_increment: NULLCreate_time: 2024-12-17 19:34:31Update_time: NULLCheck_time: NULLCollation: utf8mb4_0900_ai_ciChecksum: NULLCreate_options:Comment:
1 row in set (0.01 sec)
mysql> show create table mail\G
*************************** 1. row ***************************Table: mail
Create Table: CREATE TABLE `mail` (`t` datetime DEFAULT NULL,`srcuser` char(8) DEFAULT NULL,`srchost` char(20) DEFAULT NULL,`dstuser` char(8) DEFAULT NULL,`dsthost` char(20) DEFAULT NULL,`size` bigint DEFAULT NULL,KEY `t` (`t`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)

4.5 生成唯一的表名
如果你能创建一张temporary表, 就无所谓表名是否重复了。
Import io
Tb1_name = “tmp_tb1_%d” % os.getpid()

https://zhuanlan.zhihu.com/p/721613208
https://zhuanlan.zhihu.com/p/367182300
https://www.zhihu.com/column/c_1253693093662093312
https://www.zhihu.com/question/55720139/answer/1719997534

from multiprocessing import Process
import os# 子进程要执行的代码
def run_proc(name):print('Run child proces: %s (%s)...' % (name, os.getpid()))if __name__ == '__main__':print('Parent process %s.' % os.getpid())p = Process(target=run_proc, args=('test', ))print('Child process will start.')p.start()p.join()
print('Child process end.')

Parent process 15256.
Child process will start.
Child process end.

``
import os
from multiprocessing import Processdef child_process():print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))if __name__ == '__main__':print('Process (%s) start...' % os.getpid())p = Process(target=child_process)p.start()p.join()print('I (%s) just created a child process (%s).' % (os.getpid(), p.pid))Process (15256) start...
I (15256) just created a child process (13264).import os
import sys
from multiprocessing import Processdef child_process():# Force immediate output (critical for Windows)sys.stdout.flush()sys.stderr.flush()print(f'CHILD: I am process {os.getpid()} with parent {os.getppid()}')# Explicitly flush againsys.stdout.flush()if __name__ == '__main__':print(f'PARENT: Process {os.getpid()} starting...')p = Process(target=child_process)p.start()# Wait for child to finishp.join()  print(f'PARENT: Created child process {p.pid}')print("Note: If you don't see CHILD output above, try running this in:")print("1. A terminal (not IDE)")
print("2. Command Prompt: python script.py")PARENT: Process 15256 starting...
PARENT: Created child process 1044
Note: If you don't see CHILD output above, try running this in:
1. A terminal (not IDE)
2. Command Prompt: python script.py

使用下面的语句安全的删除它:
Drop table if exists tb1_name
第5章:与字符串共舞
5.0 引言
5.1 字符串属性

mysql> show character set;
+----------+---------------------------------+---------------------+--------+
| Charset  | Description                     | Default collation   | Maxlen |
+----------+---------------------------------+---------------------+--------+
| armscii8 | ARMSCII-8 Armenian              | armscii8_general_ci |      1 |
| ascii    | US ASCII                        | ascii_general_ci    |      1 |
| big5     | Big5 Traditional Chinese        | big5_chinese_ci     |      2 |
| binary   | Binary pseudo charset           | binary              |      1 |
| cp1250   | Windows Central European        | cp1250_general_ci   |      1 |
| cp1251   | Windows Cyrillic                | cp1251_general_ci   |      1 |
| cp1256   | Windows Arabic                  | cp1256_general_ci   |      1 |
| cp1257   | Windows Baltic                  | cp1257_general_ci   |      1 |
| cp850    | DOS West European               | cp850_general_ci    |      1 |
| cp852    | DOS Central European            | cp852_general_ci    |      1 |
| cp866    | DOS Russian                     | cp866_general_ci    |      1 |
| cp932    | SJIS for Windows Japanese       | cp932_japanese_ci   |      2 |
| dec8     | DEC West European               | dec8_swedish_ci     |      1 |
| eucjpms  | UJIS for Windows Japanese       | eucjpms_japanese_ci |      3 |
| euckr    | EUC-KR Korean                   | euckr_korean_ci     |      2 |
| gb18030  | China National Standard GB18030 | gb18030_chinese_ci  |      4 |
| gb2312   | GB2312 Simplified Chinese       | gb2312_chinese_ci   |      2 |
| gbk      | GBK Simplified Chinese          | gbk_chinese_ci      |      2 |
| geostd8  | GEOSTD8 Georgian                | geostd8_general_ci  |      1 |
| greek    | ISO 8859-7 Greek                | greek_general_ci    |      1 |
| hebrew   | ISO 8859-8 Hebrew               | hebrew_general_ci   |      1 |
| hp8      | HP West European                | hp8_english_ci      |      1 |
| keybcs2  | DOS Kamenicky Czech-Slovak      | keybcs2_general_ci  |      1 |
| koi8r    | KOI8-R Relcom Russian           | koi8r_general_ci    |      1 |
| koi8u    | KOI8-U Ukrainian                | koi8u_general_ci    |      1 |
| latin1   | cp1252 West European            | latin1_swedish_ci   |      1 |
| latin2   | ISO 8859-2 Central European     | latin2_general_ci   |      1 |
| latin5   | ISO 8859-9 Turkish              | latin5_turkish_ci   |      1 |
| latin7   | ISO 8859-13 Baltic              | latin7_general_ci   |      1 |
| macce    | Mac Central European            | macce_general_ci    |      1 |
| macroman | Mac West European               | macroman_general_ci |      1 |
| sjis     | Shift-JIS Japanese              | sjis_japanese_ci    |      2 |
| swe7     | 7bit Swedish                    | swe7_swedish_ci     |      1 |
| tis620   | TIS620 Thai                     | tis620_thai_ci      |      1 |
| ucs2     | UCS-2 Unicode                   | ucs2_general_ci     |      2 |
| ujis     | EUC-JP Japanese                 | ujis_japanese_ci    |      3 |
| utf16    | UTF-16 Unicode                  | utf16_general_ci    |      4 |
| utf16le  | UTF-16LE Unicode                | utf16le_general_ci  |      4 |
| utf32    | UTF-32 Unicode                  | utf32_general_ci    |      4 |
| utf8mb3  | UTF-8 Unicode                   | utf8mb3_general_ci  |      3 |
| utf8mb4  | UTF-8 Unicode                   | utf8mb4_0900_ai_ci  |      4 |
+----------+---------------------------------+---------------------+--------+
41 rows in set (0.01 sec)
mysql> set @s = convert('abc' using ucs2);
Query OK, 0 rows affected, 1 warning (0.00 sec)mysql> select length(@s), char_length(@s);
+------------+-----------------+
| length(@s) | char_length(@s) |
+------------+-----------------+
|          6 |               3 |
+------------+-----------------+
1 row in set (0.00 sec)mysql> set @s = convert('abc' using utf8);
Query OK, 0 rows affected, 1 warning (0.00 sec)mysql> select length(@s), char_length(@s);
+------------+-----------------+
| length(@s) | char_length(@s) |
+------------+-----------------+
|          3 |               3 |
+------------+-----------------+
1 row in set (0.00 sec)
mysql> show collation like 'latin1%';
+-------------------+---------+----+---------+----------+---------+---------------+
| Collation         | Charset | Id | Default | Compiled | Sortlen | Pad_attribute |
+-------------------+---------+----+---------+----------+---------+---------------+
| latin1_bin        | latin1  | 47 |         | Yes      |       1 | PAD SPACE     |
| latin1_danish_ci  | latin1  | 15 |         | Yes      |       1 | PAD SPACE     |
| latin1_general_ci | latin1  | 48 |         | Yes      |       1 | PAD SPACE     |
| latin1_general_cs | latin1  | 49 |         | Yes      |       1 | PAD SPACE     |
| latin1_german1_ci | latin1  |  5 |         | Yes      |       1 | PAD SPACE     |
| latin1_german2_ci | latin1  | 31 |         | Yes      |       2 | PAD SPACE     |
| latin1_spanish_ci | latin1  | 94 |         | Yes      |       1 | PAD SPACE     |
| latin1_swedish_ci | latin1  |  8 | Yes     | Yes      |       1 | PAD SPACE     |
+-------------------+---------+----+---------+----------+---------+---------------+
8 rows in set (0.01 sec)
mysql> create table t (c char(3) character set latin1);
Query OK, 0 rows affected (0.12 sec)mysql> insert into t (c) values('AAA'),('aaa'),('bbb'),('BBB');
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0mysql> select c from t;
+------+
| c    |
+------+
| AAA  |
| aaa  |
| bbb  |
| BBB  |
+------+
4 rows in set (0.00 sec)mysql> select c from t order by c collate latin1_swedish_ci;
+------+
| c    |
+------+
| AAA  |
| aaa  |
| bbb  |
| BBB  |
+------+
4 rows in set (0.00 sec)mysql> select c from t order by c collate latin1_general_cs;
+------+
| c    |
+------+
| AAA  |
| aaa  |
| BBB  |
| bbb  |
+------+
4 rows in set (0.00 sec)mysql> select c from t order by c collate latin1_bin;
+------+
| c    |
+------+
| AAA  |
| BBB  |
| aaa  |
| bbb  |
+------+
4 rows in set (0.00 sec)mysql> create table tt (c char(2) character set utf8);
Query OK, 0 rows affected, 1 warning (0.06 sec)mysql> insert into tt(c) values('cg'), ('ch'), ('ci'), ('lk'), ('ll'), ('lm');
Query OK, 6 rows affected (0.01 sec)
Records: 6  Duplicates: 0  Warnings: 0mysql> select c from tt order by c collate utf8_general_ci;
+------+
| c    |
+------+
| cg   |
| ch   |
| ci   |
| lk   |
| ll   |
| lm   |
+------+
6 rows in set (0.00 sec)mysql> select c from tt order by c collate utf8_spanish2_ci;
+------+
| c    |
+------+
| cg   |
| ci   |
| ch   |
| lk   |
| lm   |
| ll   |
+------+
6 rows in set (0.00 sec)5.2 选择字符串的数据类型
`mysql> create table t2 (c1 char(10), c2 varchar(10));
Query OK, 0 rows affected (0.06 sec)mysql> insert into t2(c1, c2) values('abc       ', 'abc         ');  #用2个tab 键
Query OK, 1 row affected (0.01 sec)mysql> select c1, c2, char_length(c1), char_length(c2) from t2;
+------+-------+-----------------+-----------------+
| c1   | c2    | char_length(c1) | char_length(c2) |
+------+-------+-----------------+-----------------+
| abc    | abc           |               4 |               5 |
+------+-------+-----------------+-----------------+
1 row in set (0.00 sec)mysql> insert into t2(c1, c2) values('abc     ', 'abc     ');       #用5个空格
Query OK, 1 row affected (0.01 sec)mysql> select c1, c2, char_length(c1), char_length(c2) from t2;
+------+----------+-----------------+-----------------+
| c1   | c2       | char_length(c1) | char_length(c2) |
+------+----------+-----------------+-----------------+
| abc    | abc              |               4 |               5 |
| abc  | abc      |               3 |               8 |
+------+----------+-----------------+-----------------+
2 rows in set (0.00 sec)

5.3 正确设置客户端连接的字符集

5.4 串字母

mysql> select 'I''m asleep', 'I\'m wide awake'-> ;
+------------+----------------+
| I'm asleep | I'm wide awake |
+------------+----------------+
| I'm asleep | I'm wide awake |
+------------+----------------+
1 row in set (0.00 sec)mysql> select "He said, ""Boo!""", "And I said, \"Yikee!\"";
+-----------------+----------------------+
| He said, "Boo!" | And I said, "Yikee!" |
+-----------------+----------------------+
| He said, "Boo!" | And I said, "Yikee!" |
+-----------------+----------------------+
1 row in set (0.00 sec)mysql> select 'Install MySql in C:\\mysql on windows';
+--------------------------------------+
| Install MySql in C:\mysql on windows |
+--------------------------------------+
| Install MySql in C:\mysql on windows |
+--------------------------------------+
1 row in set (0.00 sec)MySQL 将 0x 前缀的值解释为二进制字面量,直接查询时不会自动转换为字符串:
SELECT 0x49276D2061736C656570;  -- 显示二进制原值
+------------------------------------------------+
| 0x49276D2061736C656570                         |
+------------------------------------------------+
| 0x49276D2061736C656570                         |
+------------------------------------------------+
1 row in set (0.00 sec)
若需强制显示为字符串,需显式转换:
mysql> SELECT CONCAT('0x', HEX('I''m asleep')) AS hex_result;
+------------------------+
| hex_result             |
+------------------------+
| 0x49276D2061736C656570 |
+------------------------+
1 row in set (0.00 sec)mysql> SELECT CAST(0x49276D2061736C656570 AS CHAR) AS original_string;
+-----------------+
| original_string |
+-----------------+
| I'm asleep      |
+-----------------+
1 row in set (0.00 sec)mysql> SELECT CONVERT(UNHEX('49276D2061736C656570') USING utf8) AS original_string;
+-----------------+
| original_string |
+-----------------+
| I'm asleep      |
+-----------------+
1 row in set, 1 warning (0.00 sec)5.5 检查一个字符串的字符集或字符排序
mysql> CREATE TABLE t (->     c CHAR(10)-> ) CHARACTER SET utf8 COLLATE utf8_danish_ci;
Query OK, 0 rows affected, 2 warnings (0.34 sec)mysql> select user(), charset(user()), collation(user());
+----------------+-----------------+--------------------+
| user()         | charset(user()) | collation(user())  |
+----------------+-----------------+--------------------+
| root@localhost | utf8mb3         | utf8mb3_general_ci |
+----------------+-----------------+--------------------+
1 row in set (0.01 sec)mysql> set names-> 'latin1';
Query OK, 0 rows affected (0.01 sec)mysql> select charset('abc'), collation('abc');
+----------------+-------------------+
| charset('abc') | collation('abc')  |
+----------------+-------------------+
| latin1         | latin1_swedish_ci |
+----------------+-------------------+
1 row in set (0.00 sec)mysql> set names latin7 collate 'latin7_bin';
Query OK, 0 rows affected (0.00 sec)mysql> select charset('abc'), collation('abc');
+----------------+------------------+
| charset('abc') | collation('abc') |
+----------------+------------------+
| latin7         | latin7_bin       |
+----------------+------------------+
1 row in set (0.00 sec)
  1. 为什么第一个查询显示 latin7?
    o 这是由系统变量 character_set_connection 决定的
    o 可以查看当前字符集设置:
sql
复制
下载
SHOW VARIABLES LIKE 'character_set%';
SHOW VARIABLES LIKE 'collation%';
2.	如何确保使用 UTF-8 编码?
sql
复制
下载
-- 设置连接字符集
SET NAMES utf8mb4;-- 再次检查
SELECT CHARSET('a'), COLLATION('a');
3.	创建表时指定字符集(最佳实践)
sql
复制
下载
CREATE TABLE t (c CHAR(10)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
示例完整流程
sql
复制
下载
-- 1. 创建表(使用明确字符集)
CREATE TABLE t (c CHAR(10)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;-- 2. 插入测试数据
INSERT INTO t VALUES ('test');-- 3. 查询列字符集信息
SELECT CHARSET(c) AS column_charset,COLLATION(c) AS column_collation
FROM t
LIMIT 1;-- 4. 查询表结构元数据
SELECT column_name,character_set_name,collation_name
FROM information_schema.columns
WHERE table_schema = DATABASE()AND table_name = 't';
输出
+----------------+-------------------+
| column_charset | column_collation  |
+----------------+-------------------+
| utf8mb4        | utf8mb4_unicode_ci|
+----------------+-------------------++-------------+--------------------+-------------------+
| COLUMN_NAME | CHARACTER_SET_NAME | COLLATION_NAME    |
+-------------+--------------------+-------------------+
| c           | utf8mb4            | utf8mb4_unicode_ci|
+-------------+--------------------+-------------------+mysql> CREATE TABLE t (->     c CHAR(10)-> ) character set utf8mb4 collate utf8mb4_unicode_ci;
Query OK, 0 rows affected (0.07 sec)mysql> SELECT->     CHARSET(c) AS column_charset,->     COLLATION(c) AS column_collation-> FROM->     t;
Empty set (0.00 sec)mysql>
mysql> SELECT->     column_name,->     character_set_name,->     collation_name-> FROM->     information_schema.columns-> WHERE->     table_schema = DATABASE()->     AND table_name = 't';
+-------------+--------------------+--------------------+
| COLUMN_NAME | CHARACTER_SET_NAME | COLLATION_NAME     |
+-------------+--------------------+--------------------+
| c           | utf8mb4            | utf8mb4_unicode_ci |
+-------------+--------------------+--------------------+
1 row in set (0.00 sec)mysql> alter table t-> convert to character set utf8mb4-> collate utf8mb4_unicode_ci;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

关键区别说明
特性 utf8mb3 (旧版) utf8mb4 (推荐)
最大字符长度 3字节 4字节
支持emoji ❌ ✅
存储开销 较小 稍大
MySQL版本 所有版本 5.5.3+
为什么推荐utf8mb4?
完整支持所有Unicode字符(包括中文生僻字、emoji)

未来兼容性更好

MySQL 8.0默认使用utf8mb4

相关文章:

  • AXURE-动态面板
  • 软考 系统架构设计师系列知识点之杂项集萃(79)
  • h5的aliplayer-min.js 加密视频会走到debugger
  • 晶台光耦在手机PD快充上的应用
  • [游戏设计原理_1] 对称性和同步性 | 合作与对抗 | 公平 | 反馈循环
  • 电工基础【4】点动接线实操
  • 火语言RPA--建立界面应用
  • STM32外部中断(EXTI)以及旋转编码器的简介
  • 第三十三天打卡复习
  • Java 中 i++ 与 ++i 的区别及常见误区解析
  • 《Effective Python》第六章 推导式和生成器——使用类替代生成器的 `throw` 方法管理迭代状态转换
  • 行列式详解:从定义到应用
  • C++的多态特性及private
  • Go的隐式接口机制
  • Vue中安装插件的方式
  • 技巧小结:外部总线访问FPGA寄存器
  • 登高架设作业实操考试需要注意哪些安全细节?
  • 碰一碰发视频-源码系统开发技术分享
  • 深度学习与特征交叉:揭秘FNN与SNN在点击率预测中的应用
  • 二进制安全-OpenWrt-uBus
  • 做百度ssp的网站开发人/seo网站内容优化
  • b2c的网站有哪些/哈尔滨企业网站模板建站
  • 网站SEO容易做吗/今天发生了什么重大新闻
  • 一个网站多个域名 seo/搜索引擎网站优化和推广方案
  • 高端网站建设设计公司排名/百度指数网址是什么
  • 怎么用css做网站分片/优化大师怎么提交作业