찾다
데이터 베이스MySQL 튜토리얼MySQL命令行中给表添加一个字段(字段名、是否为空、默认值)

先看一下最简单的例子,在test中,添加一个字段,字段名为birth,类型为date类型。

相关mysql视频教程推荐:《mysql教程

mysql> alter table test add column birth date;
Query OK, 0 rows affected (0.36 sec)
Records: 0  Duplicates: 0  Warnings: 0

查询一下数据,看看结果:

mysql> select * from test;
+------+--------+----------------------------------+------------+-------+
| t_id | t_name | t_password                       | t_birth    | birth |
+------+--------+----------------------------------+------------+-------+
|    1 | name1  | 12345678901234567890123456789012 | NULL       | NULL  |
|    2 | name2  | 12345678901234567890123456789012 | 2013-01-01 | NULL  |
+------+--------+----------------------------------+------------+-------+
2 rows in set (0.00 sec)

从上面结果可以看出,插入的birth字段,默认值为空。我们再来试一下,添加一个birth1字段,设置它不允许为空。

mysql> alter table test add column birth1 date not null;
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0

居然执行成功了!?意外了!我原来以为,这个语句不会成功的,因为我没有给他指定一个默认值。我们来看看数据:

mysql> select * from test;
+------+--------+----------------------------------+------------+-------+------------+
| t_id | t_name | t_password                       | t_birth    | birth | birth1   |
+------+--------+----------------------------------+------------+-------+------------+
|    1 | name1  | 12345678901234567890123456789012 | NULL       | NULL  | 0000-00-00 |
|    2 | name2  | 12345678901234567890123456789012 | 2013-01-01 | NULL  | 0000-00-00 |
+------+--------+----------------------------------+------------+-------+------------+
2 rows in set (0.00 sec)

哦,明白了,系统自动将date类型的值,设置了一个默认值:0000-00-00。下面我来直接指定一个默认值看看:

mysql> alter table test add column birth2 date default '2013-1-1';
Query OK, 0 rows affected (0.28 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> select * from test;
+------+--------+----------------------------------+------------+-------+------------+------------+
| t_id | t_name | t_password       | t_birth    | birth | birth1     | birth2     |
+------+--------+----------------------------------+------------+-------+------------+------------+
|    1 | name1  | 12345678901234567890123456789012 | NULL       | NULL  | 0000-00-00 | 2013-01-01 |
|    2 | name2  | 12345678901234567890123456789012 | 2013-01-01 | NULL  | 0000-00-00 | 2013-01-01 |
+------+--------+----------------------------------+------------+-------+------------+------------+
2 rows in set (0.00 sec)

看到没,将增加的birth2字段,就有一个默认值了,而且这个默认值是我们手工指定的。

以上就是MySQL命令行中给表添加一个字段(字段名、是否为空、默认值)_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
MySQL에서 기존보기를 삭제하거나 수정하려면 어떻게해야합니까?MySQL에서 기존보기를 삭제하거나 수정하려면 어떻게해야합니까?May 16, 2025 am 12:11 AM

todropaViewInmysql, "dropviewifexistsview_name;"및 TomodifyAview를 사용하고 "createOrreplaceViewView_NameAsselect ...". "

MySQL보기 : 어떤 디자인 패턴을 사용할 수 있습니까?MySQL보기 : 어떤 디자인 패턴을 사용할 수 있습니까?May 16, 2025 am 12:10 AM

mysqlViewScaneFeficTicallyINGILIDESIGNPATTORNSLIKEADAPTER, DECIARATOR, FACTORY 및 OBSERVER.1) AdapterPatternAdAptSDataFromDifferentTablesinToAunifiedView.2) Decor

MySQL에서 뷰를 사용하면 어떤 장점이 있습니까?MySQL에서 뷰를 사용하면 어떤 장점이 있습니까?May 16, 2025 am 12:09 AM

viewsinmysqlarebeneficialforsimplifyingcomplexqueries, envancingsecurity, dataconsistency, andoptimizing promperformance

MySQL에서 간단한보기를 어떻게 만들 수 있습니까?MySQL에서 간단한보기를 어떻게 만들 수 있습니까?May 16, 2025 am 12:08 AM

toeteimpleviewinmysql, usethecreateviewstatement.1) definetheviewwithReateViewview_nameas.2) specifyTesLectStatementToreTrievesiredData.3) usetheViewLikeAtableForqueries.ViewsSimplifyDataAccessAndenHances, ButconSiderFormance

MySQL 사용자 명령문 생성 : 예제 및 공통 오류MySQL 사용자 명령문 생성 : 예제 및 공통 오류May 16, 2025 am 12:04 AM

toCreateUserSinmysql, usethecreateuserstatement.1) foralocaluser : createUser'LocalUser '@'localHost'IndifiedBy'SecurePassword '; 2) foremoteUser : createUser'RemoteUser'@'%'reidentifiedBy'StrongPassword ';

MySQL에서 뷰를 사용하는 한계는 무엇입니까?MySQL에서 뷰를 사용하는 한계는 무엇입니까?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations : 1) 그들은 upportallsqloperations, datamanipulation throughviewswithjoinsorbqueries를 제한하지 않습니다

MySQL 데이터베이스 확보 : 사용자 추가 및 권한 부여MySQL 데이터베이스 확보 : 사용자 추가 및 권한 부여May 14, 2025 am 12:09 AM

적절한 usermanagementInmysqliscrucialforenhancingsecurityandensuringfefficientDatabaseOperation.1) USECREATEUSERTOWDDUSERS,@'localHost'or@'%'.

MySQL에서 사용할 수있는 트리거 수에 영향을 미치는 요인은 무엇입니까?MySQL에서 사용할 수있는 트리거 수에 영향을 미치는 요인은 무엇입니까?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers, butpracticalfactorsdeteirefectiveuse : 1) ServerConfigurationimpactStriggerManagement; 2) 복잡한 트리거 스케일 스케일 사이드로드; 3) argertableSlowtriggerTriggerPerformance; 4) High ConconcercencyCancaUspriggerContention; 5) m

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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

맨티스BT

맨티스BT

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