The difference between database oracle tablespace, table, and user

The difference between table space, table, and user in oracle

Each project corresponds to a table space. The Oracle database stores physical tables through the table space. A database instance can have N table spaces, and a table space can have N tables.
Then create a user corresponding to this table space.
Therefore, when working on a large-scale project, first create a database instance, then create a table space, then create a user, and then the user specifies the table space.
User and tablespace relationship

User = Merchant
Table = Commodity
Table Space = Warehouse
A merchant can have many commodities, and a commodity can only belong to one merchant.

A product can be placed in warehouse A or warehouse B, but not in both A and B at the same time.

Warehouses are not owned by any merchant.

Merchants have a default warehouse. If no specific warehouse is specified, the goods will be placed in the default warehouse.


        Create table space and table ORACLE physically consists of the following files on disk: data files, control files and LOGFILE. A table in oracle is a table that stores data. Table space is a logical division. Easy to manage. Data table space (Tablespace) Storage of data always requires space, Oracle divides a database into several spaces according to functions to store data. Of course, the data stored on the disk is ultimately in the form of a file, so a data table space on a disk contains more than one physical file data table        

         In a warehouse, we may have multiple houses, each house has multiple shelves, and each shelf has multiple layers. We store data in the database, which is ultimately stored and managed by the unit of the data table.

        data file        

         The above concepts are logical, while data files are physical. That is to say, the data file is the real "visible thing", which is represented as a real file on the disk

 1. Create a table space (tablespace):

Format: create tablespace tablespace name datafile 'data file name' size tablespace size                

create tablespace data_test datafile 'e:\oracle\oradata\test\data_1.dbf' size 2000M;                

create tablespace idx_test datafile 'e:\oracle\oradata\test\idx_1.dbf' size 2000M;             

   (*The data file name includes the full path, the table space size is 2000M, the table is 2000M) 

 2. After the tablespace is built, users can be created          

Format: create user username identified by password default tablespace tablespace table;                

create user study identified by study default tablespace data_test; (*We create a user named study, password is study, missing tablespace is data_test - this is built in the second step.) (*The default tablespace means that the future data of the user study will be stored in data_test, that is, in the corresponding physical file e:\oracle\oradata\test\data_1.dbf if it is not specifically specified)

3. Create a user and specify a tablespace

CREATE USER cici IDENTIFIED BY cici PROFILE DEFAULT DEFAULT TABLESPACE CICI ACCOUNT UNLOCK;create user jykl identified by jykl default tablespace jykl_data temporary tablespace jykl_temp;授权给新用户GRANT connect, resource TO cici;grant create session to cici;

4. Authorize new users          

grant connect,resource to study; -- means to grant connect and resource permissions to the study user         

 grant dba to study; -- means to grant dba authority to study

5. Create a data table                 

In the above, we have created the user study We now enter the user                 

sqlplusw study/study@test  

 Then you can create a data table in the user study                

 Format: create table data table name 


oracle command to create primary key foreign key 

1. Create a student table

create table t_stu(    stuid      number(10)   primary key,    stuname    varchar2(20) not null,    stusex     varchar2(2)  default '男' check(stusex in('男','女')));     

 2. Create a curriculum

create table t_couse(    couseid     number(10)   primary key,    cousename   varchar2(20) not null,    cousetype   varchar2(4));   

3. Create a student course grade table (including primary and foreign keys)

create table t_score(    scoreid    number(10) primary key,    stuid      number(10) references t_stu(stuid),    couseid    number(10),    constraint fk_couseid foreign key(couseid)    references t_couse(couseid)    on delete cascade); 


CREATE TABLE log(log_id int(10)   unsigned NOT NULL auto_increment,log_time         datetime NOT NULL,log_user         varchar(30) NOT NULL,log_title        varchar(30) default NULL,log_content      text default NULL,PRIMARY KEY(log_id));

orale table management: 

Oracle creates a table like SQL Server, using the CREATE TABLE command to complete. To create a constraint, use the following command: Grammar format: alter table command alter table table name add constraint constraint name constraint content. Regardless of creating a table or a constraint, it is basically the same as SQL Server. Note: in Oracle, default is a value, and in SQL Server, default is a constraint, so Oracle's default setting can be created when creating a table.

Case 1:

Create a student information (INFOS) table and constraints Oracle create tables and constraints create table INFOS( STUID varchar2(7) not null, --student number student number='S'+class number+2 digit serial number STUNAME varchar2(10) not null, --name GENDER varchar2(2) not null, --gender AGE number(2) not null, --age SEAT number(2) not null, --seat number ENROLLDATE date, --admission time STUADDRESS varchar2(50) default 'address unknown', --address CLASSNO varchar2(4) not null, --class number=semester number+class number );

/ ①alter table INFOS add constraint pk_INFOS primary key(STUID) ②/alter table INFOS add constraint ck_INFOS_gender check(GENDER = 'male' or GENDER = 'female') ③/alter table INFOS add constraint ck_INFOS_SEAT check(SEAT >=0 and SEAT <= 50) ④/alter table INFOS add constraint ck_INFOS_AGE check(AGE >=0 and AGE<=100) ⑤/alter table INFOS add constraint ck_INFOS_CLASSNO check((CLASSNO >='1001' and CLASSNO<='1999') or(CLASSNO >='2001' and CLASS NO<='2999')) ⑥/alter table INFOS add constraint un_STUNNAME unique(STUNNAME) ⑦/Code analysis: ① In the Oracle code, "/" executes the statement in the buffer, because only one statement that has just been saved is stored in the buffer, and because each statement does not end with a semicolon, it is just saved in the buffer, so there is a single line "/" after each statement. ② Create a primary key constraint. ③ Create various check constraints together with ④ ⑤ ⑥ ⑦. Among them, ⑦ is a unique constraint, which means that the column value is unique, and the values ​​in the column cannot be repeated. Creating foreign key constraints in Oracle is the same as in SQL Server. For example: the existing score table is defined as follows: Case 2: Create a score table (SCORES) table and constraints Oracle creates tables and constraints create table scores( ID

ALTER TABLE SCORES ADD CONSTRAINT CK_SCORES_TERM CHECK(TERM = 'S1' OR TERM ='S2')/ALTER TABLE SCORES ADD CONSTRAINT FK_SCORES_INFOS_STUID FOREIGN KEY(STUID) REFERENCES INFOS(STUID) ②/Code Analysis: ① SQL Server can use identify Create an automatic growth column, but the automatic growth in Oracle needs to be completed with the help of a sequence (Sequence), which will be explained in the following chapters. ② Foreign key constraint definition in Oracle. Note: Table names and field names should be capitalized! oracle table creation, primary key, foreign key basic syntax - create table syntax: create table table name (field name 1 field type (length) is empty, field name 2 field type is empty);

-Add primary key alter table table name add constraint primary key name primary key (field name 1);

-Add foreign key: alter table table name add constraint foreign key name foreign key (field name 1) references association table (field name 2);

Specify the primary key and foreign key when creating the table create table T_STU( STU_ID char(5) not null, STU_NAME VARCHAR2(8) not null, constraint PK_T_STU primary key (STU_ID)); Create the primary key and foreign key together: create table T_SCORE( EXAM_SCORE number(5,2), EXAM_DATE d ate, AUTOID number(10) not null, STU_ID char(5), SUB_ID char(3), constraint PK_T_SCORE primary key (AUTOID), constraint FK_T_SCORE_REFE foreign key (STU_ID) references T_STU (STU_ID));

orale data type: type meaning CHAR (length) stores a fixed-length character string. The parameter length specifies the length, if the length of the stored string is less than length, it will be filled with spaces. The default length is 1, and the maximum length does not exceed 2000 bytes. VARCHAR2(length) stores variable-length character strings. length specifies the maximum length of the string. The default length is 1, and the maximum length cannot exceed 4000 characters. NUMBER(p, s) can store both floating-point numbers and integers. p represents the maximum number of digits (if it is a decimal, it includes the integer part, decimal part and decimal point, and p defaults to 38), and s refers to the number of decimal places. The negative number DATE can store date and time, store era, 4-digit year, month, day, hour, minute, second, and store time from January 1, 4712 BC to December 31, 4712 AD. TIMESTAMP not only stores the year, month, day, hour, minute, second, and 6 digits after the second, but also includes the time zone.

CLOB stores large text, such as storing unstructured XML documents

BLOB stores binary objects such as graphics, video, sound, etc.

2. Add default values ​​and constraints to fields when creating tables. When creating tables, you can add default values ​​to fields. For example: date field DEFAULT SYSDATE. In this way, every time you insert and modify, you can get the action time without program operations on this field. For example: IS_SEND NUMBER(1) default 1 -- whether it has been sent. You can add constraints to fields when creating tables. condition), foreign key REFERENCES table name (field name)

3. Create table example create table DEPT( DNAME varchar2(14), LOC varchar2(6), EPTNO number(2) constraint PK_DEPT primary KEY, );

create table region(  ID                    number(2) not null primary KEY,                    postcode           number(6) default '0' not null,     areaname          varchar2(30) default '' not null,                     );

 4. Naming rules and precautions when creating tables 1) Naming rules for table names and field names: must start with a letter, and can include symbols AZ, az, 0-9, _, $, # 2) Case is not distinguished 3) Reserved words in SQL are not used, and strings must be enclosed in double quotes when they must be used 4) There is a certain limit to the length of English symbols related to entities or attributes 5) Naming rules for constraint names and naming rules for grammatical constraint names. Cn (n is a number) The naming rules of constraint name strings are the same as those of table and field names 6) Precautions when using constraints System functions cannot be used in constraints, such as the field comparison between SYSDATE and other tables can be compared with the fields in this table

Precautions:

1) You can use Chinese field names when building a table, but it is better to use English field names. 2) When creating a table, put the smaller non-empty fields in the front, and put the fields that may be empty in the back.


Want to check the constraints after transaction processing SQL> alter session set constraints deferred.7. From the entity relationship diagram to the example of creating a table s_dept Precondition: there is a region table with a unique key field id SQL> CREATE TABLE s_dept (id NUMBER(7) CONSTRAINT s_dept_id_pk PRIMARY KEY, name VARCHAR2(25) CONSTRAINT s_dept_id_pk PRIMARY KEY, name VARCHAR2(25) CON STRAINT s_dept_name_nn NOT NULL, region_id NUMBER(7) CONSTRAINT s_dept_region_id_fk REFERENCES region (id), CONSTRAINT s_dept_name_region_id_uk UNIQUE(name, region_id)); 8. More complex table creation example SQL> CREATE TABLE s_emp (id NUMBER (7) CONSTRAINT s_emp_id_pk PRIMARY KEY, last_name VARCHAR2(25) CONSTRAINT s_emp_last_name_nn NOT NULL, first_name VARCHAR2(25), userid VARCHAR2(8) CONSTRAINT s_emp_userid_nn NOT NULL CONSTRAINT s_emp_userid_ uk UNIQUE, start_date DATE DEFAULT SYSDATE, comments VARCHAR2(25), manager_id NUMBER(7), title VARCHAR2(25), dept_id NUMBER(7) CONSTRAINT s_emp_dept_id_fk REFERENCES s_dept(id), salary NUMBER(11,2),commission_pct NUMBER(4,2) CONSTRAINT s_emp_commission_pct_ck CHECK (commission_pct IN(10,12.5,15,17.5,20)));

9. Example of building a table through a subquery SQL>CREATE TABLE emp_41 AS SELECT id, last_name, userid, start_date FROM s_emp WHERE dept_id = 41; SQL> CREATE TABLE A as select * from B where 1=2; as long as the structure of the table.

10. Precautions for creating tables with subqueries 1) Multiple tables can be associated and new tables can be generated with aggregate functions. Note that the selected fields must have legal field names and cannot be repeated. 2) For the table created by sub-query, only the non-empty NOT NULL constraints can be inherited, and other constraints and default values ​​are not inherited. 3) According to needs, you can use alter table add constraint ... to create other constraints, such as primary key, etc.

11. Optional parameters of Foreign Key ON DELETE CASCADE Optional parameters can be added when creating a Foreign Key: ON DELETE CASCADE It means that if you delete the content in the foreign key main table, the related content in the child table will be deleted together. If there is no ON DELETE CASCADE parameter, the child table has content, and the primary key record in the parent table cannot be deleted.

12. If there are unsatisfied records in the database table, the establishment of constraints will not succeed.

13. Example of creating and deleting synonyms for tables SQL> CREATE SYNONYM d_sum 2 FOR dept_sum_vu;

SQL> CREATE PUBLIC SYNONYM s_dept 2 FOR alice.s_dept;

SQL> DROP SYNONYM s_dept;

ORACLE's new table Create a table named INSURES create table INSURES( INSURE_NO CHAR(18) not null, --medical insurance number GETSURE_UNIT_NO CHAR(9) not null, --agency number INSURE_NAME VARCHAR2(10) not null, --name INSURE_SEX CHAR(1) not null, --sex ID_CARD_NO CHAR(18) not null, --ID card number);

Create/modify primary key, unique constraint and foreign key here INSURE_NO, GETSURE_UNIT_NO unique constraint alter table INSURES add constraint UNQ_INSURES unique (INSURE_NO, GETSURE_UNIT_NO) alter table TWN_SEED add constraint UNQ_INSURES primary key (...) create index

create index IDX_INSURES on INSURES (GETSURE_UNIT_NO, SONSURE_UNIT_NO, UNIT_NO, FAMILY_NO, HOSPS_NO)

When creating a PK, a corresponding unique index is automatically created. If not specified, the index table space is the same as the table space, but we do not recommend putting them together. create table testone(name varchar2(10 char))TABLESPACE1; ALTER TABLE TESTONE ADD CONSTRAINT PK_TESTONE1 PRIMARY KEY(NAME) USING INDEX TABLESPACE TABLESPACE2; As a good habit, do not store index and table data in the same table space


Guess you like

Origin blog.csdn.net/qq_20853741/article/details/109682566