search
HomeDatabaseMysql Tutorialmysql set跟enum记录的详解

mysql set和enum记录

Definition of a ENUM or SET column does act as a constraint on values entered into the column.?An error occurs for values that do not satisfy these conditions:

An ENUM value must be one of those listed in the column definition, or the internal numeric equivalent thereof.?The value cannot be the error value (that is, 0 or the empty string).?For a column defined as ENUM('a','b','c'), values such as '', 'd', or 'ax' are illegal and are rejected.

A SET value must be the empty string or a value consisting only of the values listed in the column definition separated by commas.?For a column defined as SET('a','b','c'), values such as 'd' or 'a,b,c,d' are illegal and are rejected.

以上为手册中说明的详细信息;

SET是一个字符串对象,可以有零或多个值,其值来自表创建时规定的允许的一列值。指定包括多个SET成员的SET列值时各成员之间用逗号(‘,’)间隔开。这样SET成员值本身不能包含逗号。 例如,指定为SET('one', 'two') NOT NULL的列可以有下面的任何值: '' 'one' 'two' 'one,two' SET最多可以有64个不同的成员。 当创建表时,SET成员值的尾部空格将自动被删除。 

当检索时,保存在SET列的值使用列定义中所使用的大小写来显示。请注意可以为SET列分配字符集和 校对规则。对于二进制或大小写敏感的校对规则,当为列分配值时应考虑大小写。 MySQL用数字保存SET值,所保存值的低阶位对应第1个SET成员。

如果在数值上下文中检索一个SET值,检索的值的位设置对应组成列值的SET成员。

例如,你可以这样从一个SET列检索数值值:

mysql> SELECT set_col+0 FROM tbl_name;

如果将一个数字保存到SET列中,数字中二进制表示中的位确定了列值中的SET成员。对于指定为SET('a','b','c','d')的列,

成员有下面的十进制和二进制值: SET成员 十进制值 二进制值 'a' 1 0001 'b' 2 0010 'c' 4 0100 'd' 8 1000 ? 如果你为该列分配一个值9,其二进制形式为1001,因此第1个和第4个SET值成员'a'和'd'被选择,结果值为 'a,d'。 

对于包含多个SET元素的值,当插入值时元素所列的顺序并不重要。

在值中一个给定的元素列了多少次也不重要。

当以后检索该值时,值中的每个元素出现一次,根据表创建时指定的顺序列出元素。

例如,

假定某个列指定为SET('a','b','c','d'):

mysql> CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));
插入值'a,d'、'd,a'、'a,d,d'、'a,d,a'和'd,a,d':
mysql> INSERT INTO myset (col) VALUES
-> ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d');
Query OK, 5 rows affected (0.01 sec)
Records: 5 ?Duplicates: 0 ?Warnings: 0

当检索时所有这些值显示为 'a,d':

mysql> SELECT col FROM myset;
+------+
| col ?|
+------+
| a,d ?|
| a,d ?|
| a,d ?|
| a,d ?|
| a,d ?|
+------+
5 rows in set (0.04 sec)

如果将SET列设置为一个不支持的值,则该值被忽略并发出警告:

mysql> INSERT INTO myset (col) VALUES ('a,d,d,s');
Query OK, 1 row affected, 1 warning (0.03 sec)
?
mysql> SHOW WARNINGS;
+---------+------+------------------------------------------+
| Level ? | Code | Message ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'col' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.04 sec)
?
mysql> SELECT col FROM myset;
+------+
| col ?|
+------+
| a,d ?|
| a,d ?|
| a,d ?|
| a,d ?|
| a,d ?|
| a,d ?|
+------+
6 rows in set (0.01 sec)

SET值按数字顺序排序。NULL值排在非NULL SET值的前面。 通常情况,可以使用FIND_IN_SET()函数或LIKE操作符搜索SET值:

mysql> SELECT * FROM tbl_name WHERE FIND_IN_SET('value',set_col)>0;
mysql> SELECT * FROM tbl_name WHERE set_col LIKE '%value%';

第1个语句找出SET_col包含value set成员的行。第2个类似,但有所不同:它在其它地方找出set_col包含value的行,甚至是在另一个SET成员的子字符串中。 下面的语句也是合法的:

mysql> SELECT * FROM tbl_name WHERE set_col & 1;
mysql> SELECT * FROM tbl_name WHERE set_col = 'val1,val2';

第1个语句寻找包含第1个set成员的值。第2个语句寻找一个确切匹配的值。

应注意第2类的比较。

将set值与'val1,val2'比较返回的结果与同'val2,val1'比较返回的结果不同。

指定值时的顺序应与在列定义中所列的顺序相同。 如果想要为SET列确定所有可能的值,使用SHOW COLUMNS FROM tbl_name LIKE set_col并解析输出中第2列的SET定义。   

刚才研究MySQL文档,发现SET类型的真正含义: ?   实际上,SET可以包含最多64个成员,其值为一个整数。这个整数 的二进制码表示该SET的值的哪些成员为真。例如有

SET('a','b','c','d'),
那么当它们的值为:
?
SET member ?Decimal value ?Binary value
-----------------------------
a     1        0001
b     ?2         0010
c     ?4        ?0100
d     ?8        ?1000
 

 如果你将9存入某个SET域,那么其二进制值为1001,也就是说这 个值中'a'和'd'为真。 ?   可以想到,如果这样的话,大家可以用LIKE命令和FIND_IN_SET() 函数来检索SET值:

?
mysql> SELECT * FROM tbl_name WHERE set_col LIKE '%value%';
mysql> SELECT * FROM tbl_name WHERE FIND_IN_SET('value',set_col)>0;
?

当然,以下SQL语句也是合法的,他们显得更加简洁:

?
mysql> SELECT * FROM tbl_name WHERE set_col = 'val1,val2';
mysql> SELECT * FROM tbl_name WHERE set_col & 1;
?
?
enum

mysql> show create table b;
+-------+-------------------------------------------------------------------------------------------------+
| Table | Create Table ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|
+-------+-------------------------------------------------------------------------------------------------+
| b ? ? | CREATE TABLE `b` (
`f1` enum('a','b','c') DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |?
+-------+-------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
?
?
mysql> select * from b;
Empty set (0.00 sec)
?
mysql> insert into b values(1);
Query OK, 1 row affected (0.00 sec)
?
mysql> insert into b values(2);?
Query OK, 1 row affected (0.00 sec)
?
mysql> insert into b values(3);?
Query OK, 1 row affected (0.00 sec)
?
mysql> insert into b values(4);?
Query OK, 1 row affected, 1 warning (0.00 sec)
?
mysql> select * from b;?
+------+
| f1 ? |
+------+
| a ? ?|?
| b ? ?|?
| c ? ?|?
| ? ? ?|?
+------+
4 rows in set (0.00 sec)
?

对于enum类型一次只能是列举的某一个数值,大约个数或是0时,插入的值为空。 ? set类型适合用于复合值(类似多项选择),enum适合于单值选择(类似单项选择)。

 以上就是mysql set跟enum记录的详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.