찾다
데이터 베이스MySQL 튜토리얼The BINARY and VARBINARY data types_MySQL

MySQL's support of the BINARY and VARBINARY data type is good, and the BINARY and VARBINARY data types are good things. And now the details. What applies here for MySQL applies for MariaDB as well.

Who supports VARBINARY

There's an SQL:2008 standard optional feature T021 "BINARY and VARBINARY data types". Our book has a bigger description, but here is one that is more up to date:

DBMS Standard-ish? Maximum length
DB2 for LUW No. Try CHAR FOR BIT DATA. 254 for fixed-length, 32672 for variable-length
DB2 for z/OS Yes. 255 for fixed-length, 32704 for variable-length
Informix No. Try CHAR. 32767
MySQL Yes. constrained by maximum row length = 65535
Oracle No. Try RAW. 2000 sometimes; 32767 sometimes
PostgreSQL No. Try BYTEA. theoretically 2**32 - 1
SQL Server Yes. 8000 for fixed-length. 2**31 -1 for variable length

Standard Conformance

Provided that sql_mode=strict_all_tables, MySQL does the right (standard) thing most of the time, with two slight exceptions and one exception that isn't there.

The first exception:

CREATE TABLE t1 (s1 VARBINARY(2));INSERT INTO t1 VALUES (X'010200');

... This causes an error. MySQL is non-conformant. If one tries to store three bytes into a two-byte target, but the third byte is X'00', there should be no error.

The second exception:

SET sql_mode='traditional,pipes_as_concat';CREATE TABLE t2 (s1 VARBINARY(50000));CREATE TABLE t3 AS SELECT s1 || s1 FROM t2;

... This does not cause an error. MySQL is non-conformant. If a concatenation results in a value that's longer than the maximum length of VARBINARY, which is less than 65535, then there should be an error.

The exception that isn't there:

The MySQL manual makesan odd claimthat, for certain cases when there's a UNIQUE index, "For example, if a table contains 'a', an attempt to store 'a/0' causes a duplicate-key error." Ignore the manual. Attempting to insert 'a/0' will only cause a duplicate-key error if the table's unique-key column contains 'a/0'.

The poemAntigonishdesccribed a similar case:

Yesterday, upon the stair,

I met a man who wasn't there.

He wasn't there again today,

I wish, I wish he'd go away..."

The BINARY trap

Since BINARY columns are fixed-length, there has to be a padding rule. For example, suppose somebody enters zero bytes into a BINARY(2) target:

CREATE TABLE t4 (s1 BINARY(2));INSERT INTO t4 VALUES (X'');SELECT HEX(s1) FROM t4;

... The result is '0000' -- the padding byte for BINARY is X'00' (0x00), not X'20' (space).

There also has to be a rule about what to do for comparisons if comparands end with padding bytes.

CREATE TABLE t5 (s1 VARBINARY(2));INSERT INTO t5 VALUES (X'0102');SELECT * FROM t5 WHERE s1 = X'010200';

... This returns zero rows. It's implementation-defined whether MySQL should

ignore trailing X'00' during comparisons, so there was no chance of getting

it wrong.

The behaviour difference between BINARY and VARBINARY can cause fun:

CREATE TABLE t7 (s1 VARBINARY(2) PRIMARY KEY);CREATE TABLE t8 (s1 BINARY(2), FOREIGN KEY (s1) REFERENCES t7 (s1));INSERT INTO t7 VALUES (0x01);INSERT INTO t8 SELECT s1 FROM t7;

... which fails on a foreign-key constraint error! It looks bizarre

that a value which is coming from the primary-key row can't be put

in the foreign-key row, doesn't it? But the zero-padding rule, combined

with the no-ignore-zero rule, means this is inevitable.

BINARY(x) is a fine data type whenever it's certain that all the valueswill be exactly x bytes long, and otherwise it's a troublemaker.

When to use VARBINARY

VARBINARY is better than TINYBLOB or MEDIUMBLOB because it has a definite

maximum size, and that makes life easier for client programs that want to

know: how wide can the display be? In most DBMSs it's more important that BLOBs can be stored separately from the rest of the row.

VARBINARY is better than VARCHAR if there should be no validity checking.For example, if the default character set is UTF8 then this is illegal:

CREATE TABLE t9 (s1 VARCHAR(5));INSERT INTO t9 VALUES (0xF4808283);

... but this is legal because character set doesn't matter:

CREATE TABLE t10 (s1 VARBINARY(5));INSERT INTO t10 VALUES (0xF4808283);

(I ran into this example on aSQL Server forumwhere the participants display woeful ignorance of Unicode).

And finally converting everything to VARBINARY is one way to avoid the annoying message "Invalid mix of collations". In fact the wikimedia folks appear to havechanged all VARCHARs to VARBINARYsback in 2011 just to avoid that error. I opine that the less drastic solution is to use collations consistently, but I wasn't there.

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
MySQL은 데이터 복제를 어떻게 처리합니까?MySQL은 데이터 복제를 어떻게 처리합니까?Apr 28, 2025 am 12:25 AM

MySQL은 비동기식, 반 동시성 및 그룹 복제의 세 가지 모드를 통해 데이터 복제를 처리합니다. 1) 비동기 복제 성능은 높지만 데이터가 손실 될 수 있습니다. 2) 반 동기화 복제는 데이터 보안을 향상 시키지만 대기 시간을 증가시킵니다. 3) 그룹 복제는 고 가용성 요구 사항에 적합한 다중 마스터 복제 및 장애 조치를 지원합니다.

설명 명세서를 사용하여 쿼리 성능을 분석 할 수있는 방법은 무엇입니까?설명 명세서를 사용하여 쿼리 성능을 분석 할 수있는 방법은 무엇입니까?Apr 28, 2025 am 12:24 AM

설명 설명은 SQL 쿼리 성능을 분석하고 개선하는 데 사용될 수 있습니다. 1. 쿼리 계획을 보려면 설명 명세서를 실행하십시오. 2. 출력 결과를 분석하고 액세스 유형, 인덱스 사용량 및 조인 순서에주의를 기울이십시오. 3. 분석 결과를 기반으로 인덱스 생성 또는 조정, 조인 작업을 최적화하며 전체 테이블 스캔을 피하여 쿼리 효율성을 향상시킵니다.

MySQL 데이터베이스를 어떻게 백업하고 복원합니까?MySQL 데이터베이스를 어떻게 백업하고 복원합니까?Apr 28, 2025 am 12:23 AM

논리 백업에 mysqldump를 사용하고 핫 백업을 위해 mysqlenterprisebackup을 사용하는 것은 mySQL 데이터베이스를 백업하는 효과적인 방법입니다. 1. MySQLDUMP를 사용하여 데이터베이스를 백업합니다 : MySQLDUMP-UROOT-PMYDATABASE> MYDATABASE_BACKUP.SQL. 2. Hot Backup : MySQLBackup- 사용자 = root-password = password-- backup-dir =/path/to/backupbackup에 mysqlenterprisebackup을 사용하십시오. 회복 할 때 해당 수명을 사용하십시오

MySQL에서 느린 쿼리의 일반적인 원인은 무엇입니까?MySQL에서 느린 쿼리의 일반적인 원인은 무엇입니까?Apr 28, 2025 am 12:18 AM

느린 MySQL 쿼리의 주된 이유는 인덱스의 누락 또는 부적절한 사용, 쿼리 복잡성, 과도한 데이터 볼륨 및 불충분 한 하드웨어 리소스가 포함됩니다. 최적화 제안에는 다음이 포함됩니다. 1. 적절한 인덱스 생성; 2. 쿼리 문을 최적화합니다. 3. 테이블 파티셔닝 기술 사용; 4. 적절하게 하드웨어를 업그레이드합니다.

MySQL의 견해는 무엇입니까?MySQL의 견해는 무엇입니까?Apr 28, 2025 am 12:04 AM

MySQL View는 SQL 쿼리 결과를 기반으로 한 가상 테이블이며 데이터를 저장하지 않습니다. 1) 뷰는 복잡한 쿼리를 단순화하고 2) 데이터 보안을 향상시키고 3) 데이터 일관성을 유지합니다. 뷰는 테이블처럼 사용할 수있는 데이터베이스에 저장된 쿼리이지만 데이터는 동적으로 생성됩니다.

MySQL과 다른 SQL 방언의 구문의 차이점은 무엇입니까?MySQL과 다른 SQL 방언의 구문의 차이점은 무엇입니까?Apr 27, 2025 am 12:26 AM

mysqldiffersfromothersqldialectsinsyntaxforlimit, 자동 점유, 문자열 comparison, 하위 쿼리 및 퍼포먼스 앤 알리 분석 .1) mysqluse Slimit, whilesqlSerVerusestOpandoracleSrownum.2) MySql'Sauto_incrementContrastSwithPostgresql'serialandoracle '

MySQL 파티셔닝이란 무엇입니까?MySQL 파티셔닝이란 무엇입니까?Apr 27, 2025 am 12:23 AM

MySQL 파티셔닝은 성능을 향상시키고 유지 보수를 단순화합니다. 1) 큰 테이블을 특정 기준 (예 : 날짜 범위)으로 작은 조각으로 나누고, 2) 데이터를 독립적 인 파일로 물리적으로 나눌 수 있습니다.

MySQL에서 어떻게 권한을 부여하고 취소합니까?MySQL에서 어떻게 권한을 부여하고 취소합니까?Apr 27, 2025 am 12:21 AM

MySQL에서 권한을 부여하고 취소하는 방법은 무엇입니까? 1. 보조금 명세서를 사용하여 grantallprivilegesondatabase_name.to'username'@'host '와 같은 부여 권한; 2. Revoke 문을 사용하여 Revokeallprivilegesondatabase_name.from'username'@'host '와 같은 권한을 취소하여 허가 변경의 적시에 의사 소통을 보장하십시오.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.