Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
MySQL Tutorial [email protected] 1 (ver. 1.0) 1. MySQL ์ค์น 2 Linux์ ์ค์น โ MySQL ์ ๊ณต์ RPM ์ ์ฌ์ฉํ ๊ฒ. โข MySQL binary๊ฐ ๋น ๋ฅด๊ฒ ๋ฐ์ /๋ณ๊ฒฝ โข ํ์ผ ์์น์์ ๋ค์๊ฐ ์ฐจ์ด โ RPM ํ์ผ: โข MySQL-server-VERSION.i386.rpm, โข MySQL-Max-VERSION.i386.rpm, and โข MySQL-client-VERSION.i386.rpm. โ ์ค์น: โข rpm -i MySQL-server-VERSION.i386.rpm MySQLclient-VERSION.i386.rpm โข ๏จ mysqld (MySQL server)๋ฅผ startํ๊ณ , ๋์์ /etc/init.d/ ์ ์ ์ ํ ํญ๋ชฉ์ ์์ฑ์ํด (๏ ์์คํ ์ด ์ผ ์ง๋ฉด ์๋์ผ๋ก ์๋ฒ๋ฅผ start) 3 โข ์ ๋ฆฌ: Windows์ ์ค์น โ IF (๊ธฐ์กด์ MySQL์ด ์์ผ๋ฉด) THEN ์ ์ง์ํฌ ๊ฒ: mysqladmin -u root -p shutdown โ ElseIF (MySQL์ด ์๋น์ค๋ก์ ์ค์น) THEN ์ ์ง์ํฌ ๊ฒ: mysqld --remove โ ElseIF (Graphical tool์ ์ฌ์ฉํ๊ณ ์ ํ๋ค๋ฉด) ์ ์ง์ํฌ ๊ฒ: โข ์ค์น โ control panel>Admin Tool SVC> SVCs Manager์์ ์๋น์ค ์ ๊ฑฐ โ setup.exe ๋๋ MSI installer๋ฅผ ์ด์ฉ โข options file์ ์์ฑ์ํฌ ๊ฒ. โข ๋ช ๋ น์ด ์ค์์ โ MySQL ์๋ฒ์ ๋๋ ํ ๋ฆฌ (c:\mysql\bin)๋ก ๊ฐ ํ Type: mysqld-max --standalone โข ๏ startup ๋ฉ์์ง. ๋ณ ๋ฌธ์ ๊ฐ ์๋ค๋ฉด MySQL์ ์๋น์ค๋ก์ ์ค์น โ ์ด์ฉํ๊ณ ์ ํ๋ server executable์ ์ ๋ ฅ: โข ์ฐธ๊ณ mysqld-max --install (์ถ์ฒ) โ Perl engine์ ์ค์นํ ๊ฒ. โข www.activestate.com/Products/ActivePerl/ โข ActivePerl comes as an MSI file. Download ํ ์ค์น. 4 Installing on OS X โข (์๋ต) 5 Configuring Your System โ (recommend) โข InnoDB table ์ฌ์ฉ โข binary logging ์ ์ผ ๋์ ๊ฒ. โข slow query logging์ ์ผ ๋์ ๊ฒ. โ help you optimize your applications. โ (options file: configuration value ์ ์ฅ) โข Windows์์, โ Global options file can be located either in your Windows directory and named my.ini or in c:\my.cnf. โ (๊ถ๊ณ ) my.ini ์ฌ์ฉ (๏.cnf๋ ๊ฐํน ๋ค๋ฅธ ํ๋ก๊ทธ๋จ์์ ์ด์ฉ) โข Unix-like ์ด์์ฒด์ ์ ๊ฒฝ์ฐ, โ Global options file์ ๋ณดํต /etc/my.cnf. โ ํ๋์ ์์คํ ์ ์ฌ๋ฌ ์๋ฒ ์ด์ ์: ์๋ฒ ๋ณ ์ ๋ณด๋ฅผ my.cnf ์ data directory์ ์ง์ . โ ๊ฐ๋ณ ์ฌ์ฉ์๋ณ๋ก ๋ค๋ฅด๊ฒ ์ ์ฅํ๋ ๊ฒฝ์ฐ: ~/.my.cnf 6 Listing 1.1 Suggested Options File [mysqld] # turn on binary logging and slow query logging log-bin log-slow-queries # InnoDB config # This is the basic config as suggested in the manual # Datafile(s) must be able to hold your data and indexes. # Make sure you have enough free disk space. ๋ฉ๋ชจ๋ฆฌ x 50%~80% innodb_data_file_path = ibdata1:10M:autoextend = buffer pool size x 25% # Set buffer pool size to -- additional memory pool size ===> log file size # 50 - 80 % of your computer's memory -- log buffer-size set-variable = innodb_buffer_pool_size=70M set-variable = innodb_additional_mem_pool_size=10M # Set the log file size to about # 25 % of the buffer pool size set-variable = innodb_log_file_size=20M set-variable = innodb_log_buffer_size=8M # Set ..flush_log_at_trx_commit to 0 if you can afford losing # some last transactions innodb_flush_log_at_trx_commit=1 7 Checking Your System Works โข ๊ธฐ๋ณธ์ฌํญ โข - mysql -u root โข PATH ์ง์ Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 4 to server version: 4.1.0-alpha-max-debug-logType 'help;' or '\h' for help. Type '\c' to clear the buffer. โ If you get a message similar to ERROR 2003: Can't connect to MySQL server on 'localhost' (10061) โ = โMySQL server๊ฐ ์ํ๋์ง ์๋๋คโ โ ๏ ์์คํ ์ ์ฌ ์๋ํ๊ฑฐ๋ ๋ค์๊ณผ ๊ฐ์ด ์๋ ์๋: โข - mysqld --standalone 8 โ Root Password ์ค์ โ set password for root@localhost=password('your password'); โข Log out (\q) ํ ๋ค์ log-in ๋จ, ๋ค์๊ณผ ๊ฐ์ด: โ mysql -u root -p โ Anonymous Account ์ญ์ use mysql; delete from user where User=''; delete from db where User=''; flush privileges; 9 ์ผ์ ์ฌ์ฉ (Basic use) Account ์ค์ โ ์ผ๋ฐ ์ฌ์ฉ์ ์ํ account ์์ฑ: grant (create, create temporary tables, delete, execute, index, insert, lock tables, select, show databases, update) on *.* to username identified by 'password'; 10 2. Quick Tour 11 MySQL Directory ๊ตฌ์กฐ โข (MySQL ํ์ผ์ default ์์น) โ Base location โข Unix : /usr/local/mysql โข Windows: C:\mysql. โ File system โข โข โข โข โข bin: MySQL server, client ๋ฐ ๊ธฐํ์ ์ ์ฉํ compiled program ์๋ก scripts: Perl scripts ์๋ก data: ์ค์ ์ ๋ฐ์ดํฐ๋ฒ ์ด์ค ๋ฐ์ดํฐ ์๋ก docs (Linux) or Docs (Windows) sql-bench (Linux) or bench (Windows): benchmarking suite. โ ์ฌ์ฉ์๊ฐ ๋ฐฉ๋ฌธํ์ง ์๋ ๋ค๋ฅธ ๋๋ ํ ๋ฆฌ โข include : header files, โข lib : libraries used by MySQL, โข share : MySQL's error messages, and examples (only in Windows, libmysql DLL์ ์ด์ฉํ๋ ์์ ). โข ** MySQL์ link๋๋ ๋ค๋ฅธ ํ๋ก๊ทธ๋จ (์: PHP) ์ค์น ์์ ๊ทธ ์์น๋ฅผ ์ ๋ ๊ฒ์ด ์ ์ฉ. 12 Executables ๊ฐ์ โข MySQL executables๋? โ bin and scripts directories โ bin directory โข mysqld (๋๋ ๊ด๋ จ ๋ณํ ๋ชจ๋)= MySQL server program โข mysql = MySQL monitor = command-line client. โข ๊ธฐํ์ ์ฃผ์ ํ๋ก๊ทธ๋จ โ โ โ โ โ mysqladmin: ๊ด๋ฆฌ ๊ธฐ๋ฅ myisamchk: damaged MyISAM table์ check/repair. mysqldump: database์ backup mysqlbinlog: binary log์ ๋ด์ฉ์ read. (disaster recovery ๋ฑ). mysqlshow: databases ๋ฐ table ์ ๋ณด๋ฅผ ๋ณด์ฌ์ค โ scripts directory โข = interpreted Perl scripts (cf.bin ๋๋ ํ ๋ฆฌ: compiled program) โข ์ค์ํ script โ Mysqlhotcopy ; database์ back up. 13 User Interface ๊ฐ์ โข 3๊ฐ์ง ์ฃผ์ UI โ mysql (=MySQL monitor), โข command-line interface โข ๊ธฐ๋ณธ ์ค์น ์์ ์์ฑ๋จ โ MySQL Control Center (MySQLCC), โข (Qt windowing toolkit์ผ๋ก ์์ฑ๋) GUI โข cross-platform โข ์ฝ๊ฒ downloadํด์ ์ค์น โ phpMyAdmin. โข Web ๊ธฐ๋ฐ interface. (Web application ๊ฐ๋ฐ์ ํธ๋ฆฌ) โข ์ฝ๊ฒ download ์ค์น 14 MySQL Monitor ๋ง๋ณด๊ธฐ โข MySQL์ ์ฐ๊ฒฐ: โข mysql -u username -p โ (์ค์์น) โข mysql -h hostname -u username -p /* ํธ์คํธ ์ง์ */ โข mysql --i-am-a-dummy -u root -p ๏ ๋ช ๋ น์ค๋ฅ์ ๋ฐ๋ฅธ damage ์๋ฐฉ โข --i-am-a-dummy option = --safe-updates. โ SHOW command: โข โข โข โข show databases; /* semicolon ์ ์ */ use databasename; show tables; describe tablename; โ \ (backslash)๋ก ์์๋๋ ๋ช ๋ น์ด โข \q, \h (for help) โข Command script โ ์ํ: โข source filename /* MySQL monitor์์ */ โข mysql -u username -p < filename /* MySQL monitor์ log-in๋์ง ์์ ๊ฒฝ์ฐ */ 15 3. DB Design Crash Course 16 Database ์ฉ์ด์ ๊ฐ๋ โข Entities and Relationships โ Entities โข = ์ค์ ์ธ๊ณ์์์ ์ฌ๋ฌผ (things in the real world). ๏ ๊ทธ ์ ๋ณด๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅํ๋ค. โข ์: employees, departments โ Relationships โข = entity๋ค ๊ฐ์ link โข ์: Works-for; an employee works for a department. โข different degrees of relationship โ one-to-one, one-to-many many-to-many 17 โข Relations or Tables โ relational database management system (RDBMS)๋ โ = supports databases that consist of a set of relations. โ ์ฌ๊ธฐ์ relation = a table of data. (์: excelํ์ผ, Fig 3.2) โข Columns or Attributes โ column and attribute ์ด ์ข ์ข ํผ์ฉ๋์ง๋ง โ a column is really part of a table, whereas an attribute relates to the real-world entity that the table is modeling. โข In Figure 3.2 โฆ โข Rows = Records = Tuples โ โฆ 18 โข Keys โ A superkey โข = table ๋ด์์ row๋ฅผ ์๋ณํด ๋ด๋๋ฐ ์ฌ์ฉ๋๋ a column (or set of columns) . โข (์) employee table์์ <employeeID, name> ๋๋ <employeeID, name, job, departmentID>๋ฅผ ํตํด row๋ฅผ ๊ตฌ๋ณ ๊ฐ๋ฅํ๋ค. ์ด๋ค ๊ฐ๊ฐ์ด super keys โ A key = a minimal superkey. โข employee table์์ employee๋ฅผ name ๋๋ employeeID์ ์ํด ๊ตฌ๋ณํ ์ ์์ผ๋ฏ๋ก ์ด๋ค ๋ชจ๋ key๊ฐ ๋๋ค. โ Candidate keys โข = keys from which we will choose the primary key. โข ๊ทธ๋ฌ๋ ์ค์ ๋ก๋ We need only the employeeID to identify a row. ์ฆ, minimal superkey (a minimized set of columns that can be used to identify a single row)์ธ employeeID๊ฐ key๊ฐ ๋๋ค. โ primary key โข = the column or set of columns that we will use to identify a single row from within a table. ์ฌ๊ธฐ์๋ employeeID๋ฅผ primary key๋ก ํ๋ค. โ Foreign keys โข represent the links between tables. 19 โข Functional Dependencies โ normalization process ์ดํด๋ฅผ ์ํด ํ์ํ ๊ฐ๋ โ ํ ์ด๋ธ ์์์ column A์ column B ์ฌ์ด์ functional dependency (A๏ B) = the value of column A determines the value of column B. โข ์: employee table์์ employeeID functionally determines the name (and all the other attributes in this particular example). โข Schemas โ = the structure (=design/ blueprint/ form) of the database without any data in it. โ ๋ค์๊ณผ ๊ฐ์ด ํํ: โข employee(employeeID, name, job, โ ๋ณธ์์์์ convention: ) โข a solid underline = the attributes that represent the primary key โข a broken underline = any attributes that represent foreign keys. โข a solid and a broken underline = Primary keys that are also foreign keys 20 Database ์ค๊ณ ์์น โข Database์ค๊ณ ์ ๊ณ ๋ คํ ์ค์ ์ฌํญ: โ โ โ โ Entity; ๋์์ด ๋๋ ์ ๋ณด๋ ๋ฌด์? ์ฆ, things or entities? Relation; โฆ ์ํ๋ (queryํ๋ ค๋ )์ ๋ณด? =โ๋ชจ๋ธ๋ง ํ๋ ค๋ ์ฌ์ ์ business rulesโ ์ ๊ทํ; redundancy and data anomalies์ ๊ฐ์ ๊ตฌ์กฐ์ ๋ฌธ์ ์ ํด๊ฒฐ!! โข ํจ์จ์ฑ (tuning/optimizing)๊ณผ ๊ด๋ฆฌ์ฑ โข Redundancy Versus Loss of Data โ Redundancy = ์ฌ๋ฌ row or table์์ ๋ฐ๋ณต๋๋ data. โ (Imagine:) โข employeeDepartment(employeeID, name, job, departmentID, departmentName) โข Figure 3.3. ; This schema design leads to redundantly storing the department name over and over. โข We can change this design as shown here: employee(employeeID, name, job, department(departmentID, name) ) โข ๏ ์ ์ฅ ๊ณต๊ฐ์ ์ค์ด๊ณ ๊ธฐํ์ ๋ช ๊ฐ์ง ๋ฌธ์ ๋ฅผ ํผํ๊ธฐ ์ํจ. โ Schema ๊ฐ์ ์ ์ผ๋์ ๋ goal; โข โreducing repetition of data without losing any informationโ. 21 โข Anomalies โ (3 types) โ ๏ flawed schema์์ ๋ฐ์ดํฐ๋ฅผ insert/delete/updateํ ๋ ๋ฐ์ . (Fig 3.3.) โ Insertion Anomalies โข ๊ธฐ์กด์ ํญ๋ชฉ๊ณผ ์์ถฉ๋๋ (match๋์ง ์๋) ๋ฐ์ดํฐ๋ฅผ insertํ๋ ๊ฒฝ์ฐ โข (์) enter an employee as working for Department 42, Development? ์ด๋ row๊ฐ ๋ง๋ ์ง ํ์ค์น ์์. โ Deletion Anomalies โข (์) all the employees of Department 128 leave on the same day. ์ด๋ ์ด๋ค ๋ชจ๋ record ๋ฅผ delete ํ๋ฉด ๋ ์ด์ Department 128๊ฐ ์กด์ฌํ์ง ์๊ฒ ๋๋ค. โ Update Anomalies โข (์) Department 128 decides to change its name to Emerging Technologies. ์ ๋ชจ๋๋ฅผ ์์ ํด์ผ ํ๋๋ฐ ๋ง์ฝ ๋๋ฝ๋๋ ์๊ฐ ์๊ธธ ๋ update anomaly. ์ด๋ ๊ด๋ จ โข Null Values โ = avoid schema designs that have large numbers of empty attributes. โ ์: 100๋ช ์ค 1~2๋ช ๋ง ํด๋น๋๋ ์ฌํญ์ด ์์ ๋ ๋๋ถ๋ถ์ด NULL์ด๋ฏ๋ก ์คํ๋ ค ๊ทธ ์ฌํญ์ ๊ธฐ์ ํ๋ ์๋ก์ด table์ ์ถ๊ฐํ๋ ํธ์ด ๋ซ๋ค. 22 ์ ๊ทํ โข Normalization โ = DB์ค๊ณ ๊ฒฐํจ ์ ๊ฑฐ ์ ์ฐจ ๏ breaking tables into smaller tables โ 1์ฐจ normal form > 2์ฐจ NF > โฆ โข "Normalization is about the key, the whole key, and nothing but the key." โข 2NF; attributes must depend on the whole key. โข 3NF; attributes must depend on nothing but the key. โข First Normal Form (1NF) โ โ โ โ each attribute/column value must be atomic. (= ์ฆ, a single value, not a set of values or another database row). Figure 3.4์ skill column์ ์ฌ๋ฌ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ฏ๋ก 1NF๊ฐ ์๋๋ค. (ํด๊ฒฐ2) Figure 3.5; ๊ทธ๋ฌ๋ redundancy๊ฐ ๋ง๋ค ๏ Figure 3.6; 23 โข Second Normal Form โ ์กฐ๊ฑด: โข all attributes that are not part of the primary key are fully functionally dependent on the primary key, AND โข the schema is already in first normal form. (์๋ฏธ) each non-key attribute must be functionally dependent on all parts of the key. ์ฆ, if the primary key is made up of multiple columns, every other attribute in the table must be dependent on the combination of these columns. โ ์: Figure 3.5. 1NF์ด์ง๋ง 2NF์ ์๋๋ค. ๏ง Primary key๊ฐ ํน์ row๋ฅผ uniquely identifyํด์ผ ํ๋ฏ๋ก. โ ์ด ์์์๋ employeeID and skill์ combination์ ์ํด์๋ง ๊ฐ๋ฅํ๋ฏ๋ก โข ์ฆ, employeeID, skill ๏ name, job, departmentID โข ๋ํ employeeID ๏ name, job, departmentID์์ name, job, departmentID๊ฐ (fully๊ฐ ์๋) partially functionally dependent on the primary key. โข Skill์ ์ด๋ฐ ์์ผ๋ก set upํ๋ฉด (row๋ฅผ uniquely identifyํ๋๋ฐ) employeeID๋ง์ผ๋ก๋ ์ถฉ๋ถ์น ์๋ค. (์: the employeeID 7513 identifies three rows. However, the combination of employeeID and skill will identify a single row ๏จ ๋ฐ๋ผ์ ์ด๋ค 2๊ฐ ๋ฅผ ํฉํ์ฌ primary key๋ก ์ด์ฉ.) โข ๏ ์ด์ ๋ฐ๋ผ: employee(employeeID, name, job, , skill) โ "What are the functional dependencies here?" โข We have employeeID, skill name, job, departmentID but we also have employeeID name, job, departmentID โข ์ฆ, we can determine the name, job, and departmentID from employeeID alone. โ "How can we put it into second normal form?" โข โข โข โข break the table into two tables!!, to wit: employee(employeeID, name, job, ) employeeSkills( , skill) == Figure 3.6์ schema. ์ด๊ฒ์ 1NF์ด๋ฉด์ ๋์์ 2NF (๏ each non-key attribute 24 is now functionally dependent on all parts of the keys.) โข Third Normal Form โ Formally, for a schema to be in 3NF, โข remove all transitive dependencies, AND โข the schema must already be in second normal form. (transitive dependency?) Figure 3.3: โ โ โ โ โ โ » employeeDepartment(employeeID, name, job, departmentID, departmentName) This schema contains the following functional dependencies: » employeeID๏ name, job, departmentID, departmentName » departmentID ๏ departmentName Primary key is employeeID, and all the attributes are fully functionally dependent on it However, we can see that we have » employeeID ๏ departmentName » employeeID ๏ departmentID and » departmentID ๏ departmentName Note also that the attribute departmentID is not a key. This relationship means that the functional dependency employeeID departmentName is a transitive dependency. ์ฌ๊ธฐ์ departmentID๋ key๊ฐ ์๋๋ฉด์๋ departmentID ๏ departmentName์ dependency๋ฅผ ๊ฐ์ง ๋๋ฐ ์ด๋ฅผ transitive dependency๋ผ๊ณ ํ๋ค. Effectively, it has a middle step (the departmentID departmentName dependency). To get to third normal form, we need to remove this transitive dependency. ์ฆ, decompose this » employee(employeeID, name, job, ) » department(departmentID, departmentName) โ (3NF์ ๋ค๋ฅธ ํํ) For every functional dependency in every table, either โข The left side of the functional dependency is a superkey (that is, a key that is not necessarily minimal). or โข The right side of the functional dependency is part of any key of that table. 25 โ ๋๋ถ๋ถ functional dependencies will be covered by the first rule! โข Boyce-Codd Normal Form (BCNF) โ = a variation on third normal form. โ Relation์ด BCNF์ด๋ ค๋ฉด ; โข 3NF + โข come under the first of the two rules. ์ฆ, all the functional dependencies must have a superkey on the left side. โ ๋๋ถ๋ถ ๋ณ๋ค๋ฅธ ์กฐ์น๋ฅผ ์ทจํ์ง ์์๋ ์ถฉ์กฑ๋๋ค. ์ด์ ์๋ฐฐ๋๋ dependency๊ฐ ์๋ค๋ฉด ์ ์์ ๊ฐ์ด ๋ค์ decompose ์์ ! โข Higher Normal Forms โ practical database design์ด๋ผ๊ธฐ ๋ณด๋ค๋ ์ฃผ๋ก ํ์ ์ ๋์. โ 3NF (or BCNF) is sufficient to avoid the data redundancy problems you will encounter. 26 ์์ฝ โข Concepts โ โ โ โ โ โ Entities are things, and relationships are the links between them. Relations or tables hold a set of data in tabular form. Columns belonging to tables describe the attributes that each data item possesses. Rows in tables hold data items with values for each column in a table. Keys are used to identify a single row. Functional dependencies identify which attributes determine the values of other attributes. โ Schemas are the blueprints for a database. โข Design Principles โ Minimize redundancy without losing data. โ Insertion, deletion, and update anomalies are problems that occur when trying to insert, delete, or update data in a table with a flawed structure. โ Avoid designs that will lead to large quantities of null values. โข Normalization โ โ โ โ โ Normalization is a formal process for improving database design. 1NF means atomic column or attribute values. 2NF means that all attributes outside the key must depend on the whole key. 3NF means no transitive dependencies. Boyce-Codd normal form (BCNF) means that all attributes must be functionally determined by a superkey. 27 4. Database, Table, Index์ ์์ฑ 28 Creating a database โข ์ํ database schema: โข โข โข โข โข employee(employeeID, name, job, ) department(departmentID, name) employeeSkills( , skill) client(clientID, name, address, contactPerson, contactNumber) assignment( , , workdate, hours) โข SQL (structured query language) โ DDL (data definition language) โ DML (data manipulation language) โข Case Sensitivity โ SQL keywords โข are not case sensitive. ๏ standard across database systems. โ Identifiers โข Database์ ๋ฐ๋ผ ๋ค๋ฅธ๋ฐ MySQL์์๋ ์ด์ํ๊ฒฝ(OS)์ ๋ฐ๋ผ โ Windows; database/table name์ not case sensitive โ Unix-like operating system; case sensitive โ MacOS X; ํ์ผ์์คํ ์ค์ ์ ๋ฐ๋ผ either case insensitive (HFS+, the default,) or case sensitive (UFS). โ ํผ๋ ํผํ๊ธฐ ์ํด ๋ชจ๋ identifier๋ฅผ case sensitive๋ก ์ทจ๊ธ! ๏ platform๊ฐ 29 portability ์ฆ์ง โ Column ๋ช , index, aliases๋ never case sensitive in MySQL. Identifiers โข ๊ฐ์ฒด (object)๋ฅผ uniqueํ๊ฒ ์๋ณ (identify)ํ๋ ๊ฒ (= name of an alias, a database, a table, a column, or an index. ) โข ์ฌ์ฉ๊ฐ๋ฅ ๋ฌธ์ = ๋ชจ๋ ๋ฌธ์. ๋จ, โ can't contain quote characters, ACSII(0) and ASCII(255). โ Database ๋ช ์ Directory๋ช ์ ์ฌ์ฉ๋๋ ๋ชจ๋ ๋ฌธ์๊ฐ ๊ฐ๋ฅํ์ง๋ง โ/, \ ๊ณผ .โ ๋ ์ ๋๋ค. โ Table ๋ช ์ filename์ ์ฌ์ฉํ๋ ๋ชจ๋ ๋ฌธ์๊ฐ ๊ฐ๋ฅํ์ง๋ง โ. ๊ณผ /โ๋ ์ ๋๋ค. โข ๊ธธ์ด = 64 ๋ฌธ์ max (๋จ,Alias ๋ช ์ 255 ๋ฌธ์ max) โข ํน์ด์ : MySQL์์๋ reserved word๋ฅผ identifier๋ก ์ด์ฉ๊ฐ๋ฅ. โ (quote๋ก ๋ฌถ๊ธฐ๋ง ํ๋ฉด) reserved word๋ฅผ identifier๋ก ์ด์ฉํ ์ ์๋ค. (์: TABLE์ด๋ผ๋ ์ด๋ฆ์ table๋ ๊ฐ๋ฅํ๋ค. ๋จ, ๊ถ๊ณ ๋์ง๋ ์์) โ (Quote๋ก ๋ฌถ์ง ์์๋ ์ฌ์ฉ๊ฐ๋ฅํ ๊ฒ) (์: DATE, TIMESTAMP๋ฅผ column ๋ช ์ผ๋ก ์ฌ์ฉํ๋ ๊ฒ) == ANSI SQLํ์ค์๋ ๋ง์ง ์๋๋ฐ ์ผ์์์๋ ๊ฐํน ์ฌ์ฉ 30 Create and Select a Database โข Create a Database โข create database employee; โข show databases; โข Select a Database โข use employee; 31 Create Tables ์คํ๊ธฐ: โข TEMPORARY; ํ์ฌ์ DB session์์๋ง visibleํ๊ณ connection์ด ์ข ๋ฃ ์ ์ญ์ ๋จ. CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)][table_options] [select_statement] โข LIKE old_table_name ; create a new table with the same schema as old_table_name. โข Other options: โข NOT NULL or NULL, or CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name LIKE old_table_name; create_definition: col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [PRIMARY KEY] [reference_definition] or PRIMARY KEY (index_col_name,...) or KEY [index_name] (index_col_name,...) or INDEX [index_name] (index_col_name,...) or UNIQUE [INDEX] [index_name] (index_col_name,...) or FULLTEXT [INDEX] [index_name] (index_col_name,...) or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...) [reference_definition] or CHECK (expr) โข DEFAULT ; default value โข AUTO_INCREMENT ; ๏ ์๋ index ๋จ. ๋ํ Indexes are automatically created for columns that are declared as PRIMARY KEY(๋ณธ sample) โข REFERENCES ; foreign key โข PRIMARY KEY = a unique, indexed column that cannot contain nulls. โข INDEX = KEY (๋จ, unique value์ผ ํ์ ๋ ์๋ค.) โข UNIQUE ; โฆ (๋จ, UNIQUE columns will also be indexed.) โข FULLTEXT ; create full-text indexes on a TEXT, CHAR, or VARCHAR column type. (MyISAM table only) โข FOREIGN KEY ; โฆ โข 32 ์คํ๊ธฐ: โข Comma-separated list of column declarations enclosed in parentheses. (์ฐธ ๊ณ ) column์ attribute๋ comma separated์ผ ํ์ ์์. โข White space์ ; (์๋ต) drop database if exists employee; create database employee; use employee; create table department ( departmentID int not null auto_increment primary key, name varchar(30) ) type=InnoDB; โข varchar์ char = ๊ฐ๋ณ๊ธธ์ด, ๊ณ ์ ๊ธธ์ด โข not null, auto_increment โข type=InnoDB (Default๋ MyISAM. InnoDB๋ foreign key์ transaction์ ์ง์ํจ) โข๋จ, MyISAM์ด ๋ค์ ๋น ๋ฆ โขReferences ์๋ฏธ ; departmentID should be referenced back to the departmentID column in the department table. (foreign key) โemployee table์ด InnoDB table์ด๊ธฐ ๋๋ฌธ์ ๊ฐ๋ฅ create table employee ( employeeID int not null auto_increment primary key, name varchar(80), job varchar(30), departmentID int not null references department(departmentID) ) type=InnoDB; 33 create table employeeSkills ( employeeID int not null references employee(employeeID), skill varchar(15) not null, primary key (employeeID, skill) ) type=InnoDB; ์คํ๊ธฐ: โข primary key โข 2-column primary key create table client ( clientID int not null auto_increment primary key, name varchar(40), address varchar(100), contactPerson varchar(80), contactNumber char(12) ) type=InnoDB; 34 create table assignment ( clientID int not null references client(clientID), employeeID int not null references employee(employeeID), workdate date not null, hours float, primary key (clientID, employeeID, workdate) ) type=InnoDB; 35 show tables; (output:) +----------------------------+ | Tables_in_employee | +---------------------------+ | assignment | | client | | department | | employee | | employeeSkills | +--------------------------+ describe department; (output:) +----------------+----------------+----------------------+--------+-------+---------+-----------------+ | Field | Type | Collation | Null | Key | Default | Extra | +----------------+----------------+-----------------------+-------+-------+----------+----------------+ | departmentID | int(11) | binary | | name | latin1_swedish_ci | YES | | varchar(20) | PRI | NULL | NULL | auto_increment| | ______ | +-----------------+---------------+----------------------+-------+------+-----------+-----------------+ 36 โข table options โ MyISAM, (default) โข = very fast and supports full-text indexing. โ ๏ previous standard ISAM type. โ InnoDB โข = ACID-compliant storage engine that supports transactions, foreign keys, and row-level locking. โ BDB (Berkeley DB) โข a storage engine that supports transactions and page-level locking. โ HEAP tables โข are stored completely in memory and are never written to disk, so they are very fast, but limited in size and are unrecoverable in the event of failure. โ MERGE tables โข allow you to combine a set of MyISAM tables with the same structure so that they can be queried as if they were one table. โข ์ต๋ ํ์ผ/ํ ์ด๋ธ size์ ํ๊ณ๋ฅผ ๊ทน๋ณตํ๋ ๋ฐฉ๋ฒ์ ํ๋๋ก ์ด์ฉ. 37 โข ๊ธฐํ์ table options (์ฃผ๋ก optimization๋ชฉ์ ) ; 1 ์ด์ธ์ ๊ฐ์ ์ง์ โ AUTO_INCREMENT = # โ AVG_ROW_LENGTH = # ;โฆ โ CHECKSUM = 1 ; 1 to turn it on. (default: Off) ; MyISAM table๋ง ์ ์ฉ โ COMMENT = "string" ;โฆ โ MAX_ROWS = # ;โฆ โ MIN_ROWS = # ;โฆ โ PACK_KEYS = {0 | 1 | DEFAULT} โข By default, MySQL packs (compresses) strings in keys (์ฆ, CHARs, VARCHARs, and TEXT). โข 1 = all keys will be packed; 0 = none will be packed. โ PASSWORD = "string" ; does nothing in the standard version of MySQL. โ DELAY_KEY_WRITE = {0 | 1} ; key update๋ฅผ table์ด closed๋ ๋๊น์ง delay์ํด. โข (๋จ, MyISAM table์๋ง ์ ์ฉ) โ ROW_FORMAT= {default | dynamic | fixed | compressed } ; specify the storage format for rows. (๋จ, MyISAM tables์๋ง ์ ์ฉ). โ RAID_TYPE= {1 | STRIPED | RAID0 } RAID_CHUNKS=# RAID_CHUNKSIZE=# โข RAID configuration ์ค์ (optimization ์ฉ) โ UNION = (table_name,[table_name...]) ; only for MERGE tables โ INSERT_METHOD= {NO | FIRST | LAST } ; only for MERGE tables โ DATA DIRECTORY="absolute path to directory" ; โฆ โ INDEX DIRECTORY="absolute path to directory" ; index๋ณด๊ด์ฅ์ ์ง์ โข (์ฐธ๊ณ ) CREATE TABLE ๋ฌธ์ฅํ์์์ ๋ง์ง๋ง์ SELECT ๋ฌธ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ 38 โ ๏ to fill the new table with the data that is returned by the SELECT statement. Column and Data Type โข (3 Basic column types) โ Numerical types / String or text types/ Date and time types โข Numerical types โ ๊ฐ์ โ int (integer=exact type) ๋ฐ float (floating-point = approximate numerical type). -ํํํ์์ ์ง์ : salary decimal(10, 2) โ UNSIGNED and/or ZEROFILL » UNSIGNED ; column contains only zero or positive numbers. » ZEROFILL ; number will be displayed with leading zeroes. โข NUMERIC or DECIMAL (= DEC) โ store exact floating-point values (์: monetary values.) โ same range as double-precision floating-point numbers. โข INTEGER and Variations (INT) โ = a standard integer, (in 4 bytes ๏ a range of 232 possible values) โ several variations on INT: 1/2/3/4/8 » TINYINT (1 byte ๏ 28 possible values). = BIT = BOOL » SMALLINT (2 bytes ๏ 216 possible values) » MEDIUMINT is 3 bytes (224 possible values). » BIGINT is 8 bytes (264 possible values). โข FLOAT โ = a single-precision floating-point number. โ (ํํ) 1.18x10-38 ~ 3.40x1038 ๋๋ ๋น์ทํ ๋ฒ์์ negative numbers. โข DOUBLE โ = a double-precision floating-point number=REAL=DOUBLE PRECISION. โ (ํํ) 2.23x10-308 ~ 1.80x10308 ๋๋ ๋น์ทํ ๋ฒ์์ negative numbers. 39 โข String and Text Types โ CHAR โข store fixed-length strings. โข ๊ธธ์ด๋ฅผ ()๋ก ์ง์ . Max=255, Default=1 โข ๊ณ ์ ๊ธธ์ด๋ก ๋ณด๊ด๋ ํ retreive๋ ๋ space๊ฐ stripped ๋จ. โ CHAR takes up more space on disk than variable-length string. โ Trade-off: faster to retrieve rows (์ฆ, CHAR, numeric, or date). โข Both CHAR and VARCHAR types can be preceded with the keyword NATIONAL, meaning to restrict the contents to the standard character set. (default์ด๋ฏ๋ก cross-platform compatibility์์๋ง ์๋ฏธ๊ฐ ์์) โข CHAR์ VARCHAR ๋ชจ๋ ๋ค์ BINARY๋ฅผ ํ์ํ ์ ์๋ค. ; they should be treated as case sensitive when evaluating string comparisons. (default๋ case insensitive). โ VARCHAR โข variable-length strings. (0 to 255). โ TEXT, BLOB, and Variations โข TEXT types ; storing longer text than in a CHAR or VARCHAR. โข BLOB ; Binary Large OBject. โ These types are the same except that BLOBs are for binary data rather than text. Comparisons on BLOBs are case sensitive, and on TEXTs, they are not. โข They are both variable in length, but both come in various sizes: โ โ โ โ TINYTEXT or TINYBLOB ; up to 255 (that's 28-1) characters(bytes). TEXT or BLOB ; up to 65,535 (216-1) characters or bytes (64KB). MEDIUMTEXT or MEDUIMBLOB ; up to 16,777,215 (224-1) chars/ bytes (16MB). LONGTEXT or LONGBLOB ; up to 4,294,967,295 (232-1) characters or bytes (4GB). โ ENUM โข a set of possible values. ์: gender enum('m', 'f') ๋จ, NULL๊ฐ์ ๊ฐ์ง ์ ์์ผ๋ฏ๋ก ์ค์ ๋ m, f, NULL, or error. โ SET 40 โข ENUM๊ณผ ์ ์ฌ. ๋จ, rows may contain a set of values from the enumerated set. โข Date and Time Types โ DATE โข in ISO year-month-day order, avoiding trans-Atlantic arguments. โข Dates are displayed as YYYY-MM-DD. โ TIME โข HH:MM:SS. โ DATETIME โข = a combination of the previous types. โข YYYY-MM-DD HH:MM:SS. โ TIMESTAMP โข If you do not set this column in a particular row, or set it to NULL, it will store the time that row was inserted or last changed. โข When you retrieve a timestamp, it will be displayed in the DATETIME format. (version 4.0 to 4.1๊ณผ๋ ๋ฌ๋ผ์ง. โฆ) โ YEAR โข you can declare it as YEAR(2) or YEAR(4) to specify the number of digits. YEAR(4) is the default. โข YEAR(2) represents the range 1970 to 2069. 41 Creating Indexes โข ์ผ๋ฐ๋ก โ PRIMARY KEY, KEY, UNIQUE, or INDEX ๋ก ์ ์ธ๋ column์ will be indexed. โข CREATE INDEX โ CREATE INDEX statement is mapped to an ALTER TABLE statement before being executed. โ (์:) create index name on employee(name); โ create index statement์๋ option์ด ๋ง์ง ์๋ค. โข CREATE UNIQUE index ; enforce a uniqueness constraint. โข CREATE FULLTEXT ; create a full-text index on a MyISAM table. โข Limit indexes on char and varchar types to index just the first few characters in each field. โ ์: create index part_name on employee(name(5)); โ ์ด์ : indexes on text types are not as efficient as indexes on numeric types, and just indexing the first few characters improves performance. 42 Databases, Tables, Index์ ์ญ์ โข (๋ช ๋ น์ด) drop database employee; โ optional IF EXISTS clause before the database name โข DROP TABLE statement: โ DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name,...] โข TEMPORARY ; for dropping temporary tables. โข ๊ธฐํ ์๋ต โข DROP INDEX statement โ drop index part_name on employee; 43 Altering Existing Table Structures โข ALTER TABLE ์คํ๊ธฐ: ํน์ด์ฌํญ๋ง ๊ฒํ : โข CHANGE / MODIFY (๊ณตํต); column definition or table์์์ position ๋ณ ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...] ๊ฒฝ. โข DROP COLUMN ; deletes a column alter_spec: from the table (๋น๊ต) DROP PRIMARY ADD [COLUMN] create_definition [FIRST | AFTER col_name ] KEY and DROP INDEX delete just the or ADD [COLUMN] (create_definition, create_definition,...) associated index for that column. or ADD INDEX [index_name] (index_col_name,...) โข DISABLE KEYS ; stop updating indexes for a MyISAM table only. or ADD PRIMARY KEY (index_col_name,...) ENABLE KEYS turns index updating or ADD UNIQUE [index_name] (index_col_name,...) back on. or ADD FULLTEXT [index_name] (index_col_name,...) โข RENAME ; change name of a table. or ADD [CONSTRAINT symbol] FOREIGN KEY [index_name] โข ORDER BY ; put the rows in the (index_col_name,...) newly altered table in a particular [reference_definition] order (This order will not be or ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT} maintained as the data in the table or CHANGE [COLUMN] old_col_name create_definition changes over time.) [FIRST | AFTER column_name] โข table_options ; lets you specify the same table options as at the or MODIFY [COLUMN] create_definition [FIRST | AFTER col_name] end of the CREATE TABLE or DROP [COLUMN] col_name statement. or DROP PRIMARY KEY or DROP INDEX index_name or DISABLE KEYS or ENABLE KEYS 44 or RENAME [TO] new_tbl_name or ORDER BY col_name or table_options 5. Inserting, Deleting, and Updating Data 45 Listing 5.1 employee_data.sql use employee; delete from department; insert into department values (42, 'Finance'), (128, 'Research and Development'), (NULL, 'Human Resources'), (NULL, 'Marketing'); delete from employee; insert into employee values (7513,'Nora Edwards','Programmer',128), (9842, 'Ben Smith', 'DBA', 42), (6651, 'Ajay Patel', 'Programmer', 128), (9006, 'Candy Burnett', 'Systems Administrator', 128); 46 delete from employeeSkills; insert into employeeSkills values (7513, 'C'), (7513, 'Perl'), (7513, 'Java'), (9842, 'DB2'), (6651, 'VB'), (6651, 'Java'), (9006, 'NT'), (9006, 'Linux'); delete from client; insert into client values (NULL, 'Telco Inc', '1 Collins St Melbourne', 'Fred Smith', '95551234'), (NULL, 'The Bank', '100 Bourke St Melbourne', 'Jan Tristan', '95559876'); delete from assignment; insert into assignment values (1, 7513, '2003-01-20', 8.5); 47 select * from department; +------------------+---------------------------+ | departmentID | name | +------------------+---------------------------+ | 42 | Finance | | 128 |Research and Develop | | 129 | Human Resources | | 130 | Marketing | +-----------------+-----------------------------+ 4 rows in set (0.01 sec) 48 ์คํ๊ธฐ: โข LOW PRIORITY or DELAYED. (general form of the INSERT statement) INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ((expression | DEFAULT),...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expression, ... ] or INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT ... or INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name SET col_name=(expression | DEFAULT), ... [ ON DUPLICATE KEY UPDATE col_name=expression, ... ] ; (๊ณตํต) insertion will be delayed until no client is trying to read from the table. ; (์ฐจ์ด์ ) LOW PRIORITY will block the inserting client and DELAYED will not. ์ฆ, โขLOW PRIORITY insert; ์ ์ ๊ธฐ๋ค๋ฆฐ ํ query์ ํ โขDELAYED; you will be told OK and can continue running queries, but you need to remember that the insert will not be performed until the table is not in use.) โข IGNORE ; chiefly useful when inserting multiple rows. ๋ณดํต ์ ๊ท ์ ๋ ฅ row๊ฐ ๊ธฐ์กด์ row์ PRIMARY KEY or UNIQUE value์ clash๋๋ฉด errorํ์ ํ insert ์์ฒด๊ฐ abort๋์ง๋ง IGNORE๋ก ์ง์ ํ๋ฉด, error will be ignored and the insert will continue and will attempt to insert the next row. โข DEFAULT ; column์ default value ์ง์ . โข ON DUPLICATE KEY UPDATE ; (๋ท์ฅ) 49 โขON DUPLICATE KEY UPDATE โ Primary key ๋๋ unique value๊ฐ clash๋ ๋ ์ ์ ํ ์ฒ๋ฆฌ๋ฐฉ ๋ฒ ์ ์. ์ฆ, change the primary key or unique value in the row already in the table so that it no longer clashes with the new row. โ (์:) create table warning ( employeeID int primary key not null references employee(employeeID), count int default 1 ) type =InnoDB; insert into warning (employeeID) values (6651) on duplicate key update count=count+1; ์คํ๊ธฐ: (๋ค์ ์ํฉ์ ์ ์ฉ) unique event ๋ฐ์ ์ ์ด๋ฅผ ๊ธฐ๋ก (record)ํ ๋ฟ ์๋๋ผ ์ด๋ค action์ ์ทจํ๊ณ ์ ํ ๋ (์1) increment a counter when non-unique events occur. (์2) ๊ฐ์ข logging (์์ employee DB์์ we will record employees who have been given a warning in the table warning.) ์ด๋ค ์ฌ๋์ warning์ ๊ธฐ๋กํ ๋ count์ default ๊ฐ์ด 1์ผ ๋, ์ถ๊ฐ์ (subsequent) insert ๋ฐ์ ์ (๋์ผ employeeID์ ๋ํด) ON DUPLICATE KEY UPDATE clause ์ ์ํด counter ๊ฐ์ ์ฆ๊ฐ. 50 Using REPLACE (general form of REPLACE) REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] VALUES (expression,...),(...),... or REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] SELECT ... or REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name SET col_name=expression, col_name=expression,... 51 Using DELETE โข delete from department; โ ๏ delete all the rows from the table. โ ์ค์์ ๋๋น:โ-safe-updates ๋๋ โ-i-am-a-dummy option โข delete from department where name='Asset Management'; ์คํ๊ธฐ: delete employee, employeeSkills DELETE [LOW_PRIORITY] [QUICK] FROM table_name [WHERE where_definition] [ORDER BY ...] [LIMIT rows] or DELETE [LOW_PRIORITY] [QUICK] table_name[.*] [, table_name[.*] ...] FROM table-references [WHERE where_definition] or DELETE [LOW_PRIORITY] [QUICK] FROM table_name[.*] [, table_name[.*] ...] USING table-references [WHERE where_definition] from employee, employeeSkills, department where employee.employeeID = employeeSkills.employeeID and employee.departmentID = department.departmentID and department.name='Finance'; delete from employee, employeeSkills using employee, employeeSkills, department where employee.employeeID = employeeSkills.employeeID and employee.departmentID = department.departmentID and department.name='Finance'; (๋ค๋ฅธ optional clauses) · * LOW_PRIORITY clause; (์๋ต) · * QUICK ; DELETE ์ index์ ๋ํ housekeeping ์ผ๋ถ์์ ์๋ต ๏ speed up · ; ORDER BY ; row ์ญ์ ์์ ์์ ์ง์ - LIMIT ๋ฌธ๊ณผ ํจ๊ป ์ฌ์ฉํ ๋ฉด ์ ์ฉ โ(์) delete the oldest n rows from a table. 52 ; LIMIT ; DELETE ๋ก ์ญ์ ๋ ์ ์๋ ์ต๋ row ์ซ์๋ฅผ ์ค์ Using TRUNCATE โข delete all the rows from a table. โข ์: TRUNCATE TABLE employee; โข DELETE ๋ฌธ๋ณด๋ค ๋น ๋ฅด๋ค. (๏ works by dropping the table and re-creating it empty. ) โข ๋จ, TRUNCATE is not transaction safe. 53 Using UPDATE (general form of the UPDATE statement) UPDATE [LOW_PRIORITY] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition] [ORDER BY ...] [LIMIT rows] or UPDATE [LOW_PRIORITY] [IGNORE] tbl_name [, tbl_name ...] SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition] โข ํน์ด์ฌํญ ์์. 54 Uploading Data with LOAD DATA INFILE (general form of the LOAD DATA INFILE statement) LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'fileName.txtโ [REPLACE | IGNORE] INTO TABLE tbl_name [FIELDS [TERMINATED BY '\t'] [[OPTIONALLY] ENCLOSED BY ''] [ESCAPED BY '\\' ] ] [LINES TERMINATED BY '\n'] [IGNORE number LINES] [(col_name,...)] โข โข bulk insert data from a text file into a single table (INSERT ๋์ ) Listing 5.2 department_infile.txt 42 Finance 128 Research and Development NULL Human Resources NULL Marketing load data local infile 'department_infile.txtโ into table department; โข โข ์คํ๊ธฐ: optional clauses: · * LOW PRIORITY clause ; (์๋ต) * CONCURRENT allows other clients to read from the table while the bulk insert is going on. · * LOCAL; means the data file is on client machine. (LOCAL์ด ์์ผ๋ฉด MySQL์ ์๋ฒ์์ infile ์ ์ฐพ์) · * ๋ฐ์ดํฐ insert๊ณผ์ ์์ clash ๋ฐ์ ์ 2๊ฐ์ง ๋์ฒ: - REPLACE replace old row with new row, - IGNORE tells MySQL to keep old row. · * FIELDS and LINES ; infile์ ์๋ก๋ ๋ฐ์ดํฐ๊ฐ layout๋๋ ๋ฐฉ๋ฒ์ ์ง์ . ์ผ๋ฐ์ ์ผ๋ก๋ default๊ฐ ์ด ์ฉ.โeach row on a new line, column values separated by tabs. We can also enclose column values in quotes and use the backslash character to escape any special characters (like single quotes) that might confuse MySQL. · * IGNORE number LINES ; ignore the first number lines in the infile. · * ๋ง์ง๋ง ์ค์ col_name; allows you to specify that you only want to read data into some of the table's columns. ๋ค๋ฅธ DB format, spreadsheet, CSV file ๋ก๋ถํฐ data convertํ๋ ๋ฐ์ ์ ์ฉ. (์ฃผ์) FILE privilege๊ฐ ํ์ํจ. ๏ security reasons (์) to stop from loading in /etc/passwd 55 โข Listing 5.3 new_programmers.csv Name,Job,DepartmentID Julia Lenin,Programmer,128 Douglas Smith,Programmer,128 Tim O'Leary,Programmer,128 โข Load this data into employee table with: load data infile 'e:\\new_programmers.csvโ into table employee fields terminated by ',โ lines terminated by '\nโ ignore 2 lines (name, job, departmentID); โข (์ฃผ์์ฌํญ) โ Windows/DOS-style path์์์ backslash์ฒ๋ฆฌ ๏ 'e:\\new_programmers.csv'. โ CSV file are terminated by commas โ first two lines as a header should be ignored. 56 6. Querying MySQL 57 Overview of SELECT โข General form: SELECT columns FROM tables [WHERE conditions] [GROUP BY group [HAVING group_conditions]] [ORDER BY sort_columns] [LIMIT limits]; โข โขํน์ column์ ์ ํ select name, employeeID from select * from department; ๏จ employee; ๏จ +--------------------+---------------------------------+ +-----------+----------+ | departmentID | name | | name | employeeID | +--------------------+---------------------------------+ +-----------+----------+ | 42 | Finance | | Ajay Patel | 6651 | | 128 | Research and Development | | Nora Edwards | 7513 | | 129 | Human Resources | | Candy Burnett | 9006 | | 130 | Marketing | | Ben Smith | 9842 | +--------------------+---------------------------------+ +------------+---------+ 4 rows in set (0.00 sec) 4 rows in set (0.00 sec) Simple Queries 58 โข Specifying Absolute Databases and Tables select employee.name from employee; ๏จ +-----------------+ | name | +-----------------+ | Ajay Patel | | Nora Edwards | | Candy Burnett | | Ben Smith | +------------------+ 4 rows in set (0.41 sec) โ ๋ง์ฐฌ๊ฐ์ง๋ก, โข select name from employee.employee; ๏จ โข (์์ ๋์ผํ ๊ฒฐ๊ณผ) โ ๊ฐ๊ธ์ database.table.column syntax: โข select employee.employee.name from employee; 59 โข Aliases โ rename columns or expressions in a SELECT statement select name as employeeName from employee; ๏จ +----------------------+ | employeeName | /* ์ฌ๊ธฐ์ employeeName์ด alias์ด๋ค */ +----------------------+ | Ajay Patel | | Nora Edwards | | Candy Burnett | | Ben Smith | +----------------------+ 4 rows in set (0.01 sec) โ ๋ค๋ฅธ ์: โข select e.namefrom employee as e; ๏จ Alias๋ฅผ ์ฐ๋ ๋ง๋ ๊ฒฐ๊ณผ๋ ๊ฐ๋ค. โ ์์ ์์์ keyword AS๋ optional. ์ฆ, select name employeeName from employee; select e.name from employee e; AND 60 ํน์ Row์ ํ์ ์ํ WHERE Clause ์ฌ์ฉ โข ๊ฐ๋จํ ์: select employeeID, name ๏จ +----------------+-----------------+ from employee | employeeID | name | where job='Programmer'; +-----------------+----------------+ | 6651 | Ajay Patel | | 7513 | Nora Edwards | +-----------------+----------------+ 2 rows in set (0.42 sec) โ ์ฌ์ฉํ ์ ์๋ ์ฃผ์ operators: โข =, <>, >, <, >=, <= (๋น๊ต ์ ์์ ์ ์ฉ ๊ฐ๋ฅ) (์: somevalue > someothervalue*10) โข IS NULL , IS NOT NULL (์ด๊ฒ์ somevalue=NULL ์ฌ๋ถ test์ ์ฌ์ฉ ๋ถ๊ฐ.) โข ํ์ค Boolean operators (AND, OR, NOT) ์ฌ์ฉ๊ฐ๋ฅ. ๋จ, ๋น๊ต operator๋ณด๋ค๋ ํ ์์ (์: salary > 30000 AND salary < 50000) โ ๋ง์ด ์ฐ์ด๋ ํจ์: count() ; query์ ๋ฐ๋ฅธ row ์ซ์ count (์) select count(*) from employee; ๏จ โhow many rows in โฆโ โ ๋ํ precedence ์กฐ์ by grouping expressions with parentheses. ์: select * from assignment where employeeID=6651 and hours > 8; โ (์ฃผ์) WHERE ์๋ column aliases๋ฅผ ์ฌ์ฉ๋ถ๊ฐ(=ANSI SQL ํ๊ณ) โ ์ด์ : alias ์ฒ๋ฆฌ๋ column ๊ฐ์ WHERE ์กฐ๊ฑด์ด ๊ฒ์ฌ๋๋ ์์ ์๋ ์ ์ ์๋ ์ํ 61 Removing Duplicates with DISTINCT โข ์: select count(job) from employee; +--------------+ | count(job) | +--------------+ | 4 | +--------------+ 1 row in set (0.01 sec) โข Misleading! ์ ํํ ๋ฐฉ๋ฒ์: select count(distinct job) from employee; +------------------------+ | count(distinct job) | +------------------------+ | 3 | +-----------------------+ 1 row in set (0.05 sec) โข ์ฆ, how many different values are in the job column 62 Using the GROUP BY Clause select count(*), job from employee group by job; ๏จ +------------+-----------------------------+ | count(*) | job | +------------+-----------------------------+ | 1 | DBA | | 2 | Programmer | | 1 | Systems Administrator | +------------+-------------------------------+ 3 rows in set (0.04 sec) โข MySQL and ANSI SQL ์์์ 2๊ฐ์ง ์ฐจ์ด์ : โ ANSI SQL; you must group by all the columns you have listed in the initial SELECT clause. โ MySQL; you can have additional fields in the SELECT clause that are not in the GROUP BY clause. ๋ํ group order์ sort๋ ๊ฐ๋ฅ. ์: select count(*), job from employee group by job desc; ๏จ +----------+-----------------------------+ | count(*) | job | +----------+-----------------------------+ | 1 | Systems Administrator | | 2 | Programmer | | 1 | DBA | +----------+-----------------------------+ 3 rows in set (0.04 sec) 63 โข Selecting Particular Groups with HAVING โ GROUP BY with a HAVING clause ; SELECT with a WHERE clause์ ์ ์ฌ. ์: select count(*), job from employee group by job having count(*)=1; ๏จ +----------+--------------------------------+ | count(*) | job | +----------+--------------------------------+ | 1 | DBA | | 1 | Systems Administrator | +----------+--------------------------------+ 2 rows in set (0.05 sec) โ WHERE์ HAVING โข WHERE ; ๊ฐ๋ณ row์ ๋ํ ์กฐ๊ฑด test๋ก์ ์ผ์์ ์ผ๋ก ๋ง์ด ์ฌ์ฉ๋จ. โข HAVING; whole group์ ๋ํ ์กฐ๊ฑด ํ ์คํธ. โข Sorting Search Results with ORDER BY select * from employee order by job asc, name desc; ๏จ +-----------------+-------------------+-------------------------------+-------------------+ | employeeID | name | job | departmentID | +-----------------+-------------------+-------------------------------+-------------------+ | 9842 | Ben Smith | DBA | 42 | โฆ | 9006 | Candy Burnett | Systems Administrator | 128 | +-----------------+--------------------+------------------------------+-------------------+ 4 rows in set (0.02 sec) 64 โ Default๋ ASC. ๋จ, ORDER BY ๋ฅผ ์ง์ ํ์ง ์์ผ๋ฉด ์ฐ์ถ๋ฌผ์ ์์๋ ์ฅ๋ดํ ์ ์๋ค. Limiting Search Results with LIMIT โ ์: select * from employeeSkills limit 5; /*๏จ only the first five rows that match the selection criteria */ +-----------------+-------+ | employeeID | skill | +-----------------+-------+ | 6651 | Java | | 6651 | VB | | 7513 |C | | 7513 | Java | | 7513 | Perl | +-----------------+-------+ 5 rows in set (0.44 sec) โ ๋ค๋ฅธ ์ (to retrieve rows 6 through 8 from the preceding query): select * from employeeSkills limit 5, 3; /*๏จ ์ ํ๋ผ๋ฏธํฐ=offset (start point), ๋ค ํ๋ผ๋ฏธํฐ = ์ํ๋ max no of rows*/ โ Row numbering starts from zero when specifying offsets (์์ ์์์ 6th row ๋ offset 5๋ก ํํ). (์์ ์์์๋ rows 0 to 4, ๋ค์ ์์์๋ rows 5 to 7.) โ second parameter๊ฐ -1 ์ด๋ฉด offset ๋ถํฐ table์ ๋๊น์ง ์์ฑ๋จ. โ LIMIT ์ ORDER BY๋ฅผ ํจ๊ป ์ฌ์ฉํ๋ฉด ์ ์ฉ. (๋จ, ORDER BY ์์ด ์ฌ์ฉํ๋ฉด ์๋ฌด๋ฐ ๋ ผ๋ฆฌ์ ์์ ์์ด record๋ฅผ retrieveํจ.) 65 โ ํนํ Web or GUI applications ๊ฐ๋ฐ์ ์ ์ฉ. ๏ easy mechanism for paging 7. Advanced Queries โข ์ฌ๋ฌ table์ ๋ํ join โ Natural, inner, and cross joins โ Straight joins โ Left and right joins โข Subquery์ ์์ฑ๊ณผ ์ด์ฉ โข SELECT๋ฌธ์์์ options 66 Using Joins to Run Queries over Multiple Tables โข โข (๊ฐ์) RDBMS์ ํน์ง=relationships= table๋ค ์ฌ์ด์ link๋ก๋ถํฐ ์ ๋ณด์ ํ=join Joining Two Tables โ ์ (employee name๊ณผ ๊ทธ๋ค์ด ๊ทผ๋ฌดํ๋ department name): select employee.name, department.name from employee, department where employee.departmentID = department.departmentID; ๏จ +---------------------+-----------------------------------+ | name | name | +---------------------+-----------------------------------+ | Ben Smith | Finance | โฆ +--------------------+-------------------------------------+ 4 rows in set (0.42 sec) โ WHERE ์์ด ์ฌ์ฉํ๋ฉด โall possible combinations of โฆ = Cartesian product of the two tables. โ ์ด ์์์๋ employee.departmentID = department.departmentID๊ฐ join condition (= the link between the tables based on the foreign keys in our original schema). โ ๋ํ readability๋ฅผ ์ํด์๋ aliases์ฌ์ฉ. select employee.name as employeeName, department.name as departmentName from employee, department where employee.departmentID = department.departmentID; ๏จ +----------------------+--------------------------+ | employeeName | departmentName | +----------------------+--------------------------+ | Ben Smith | Finance | โฆ 67 +---------------------+---------------------------+ 4 rows in set (0.55 sec) โข Joining Multiple Tables โ ์: Telco Inc.๋ผ๋ ๊ณ ๊ฐ์ ํ ๋น๋ department's employees๋ฅผ ์ฐพ๊ณ ์ ํจ. โ ํด๋ฒ: client name > clientID > assignments in the assignment table > employeeIDs from the assignment table > ids of the departments they work for from employee table > department name from department table select department.name from client, assignment, employee, department where client.name='Telco Incโ and client.clientID = assignment.clientID and assignment.employeeID = employee.employeeID and employee.departmentID = department.departmentID; ๏จ +------------------------------------+ | name | +------------------------------------+ | Research and Development | +------------------------------------+ 1 row in set (0.00 sec) โ ์ด ์์์ โฆ (guideline) If you are joining n tables, in most cases, you will have a link between each pair of tables, and therefore have n-1 join conditions. (Fig 7.1) 68 โข Self Joins - Joining a Table to Itself โ ์ด๊ฒ๋ ๊ฐ๋ฅํ๋ค. โข Find Nora Edwards์ ๊ฐ์ ๋ถ์(department)์์ ๊ทผ๋ฌดํ๋ ์ฌ๋.โ โข (ํด๋ฒ) find the departmentID Nora works for from the employee table > employee table์์ ๊ทธ deparment์ ๊ทผ๋ฌดํ๋ employee๋ฅผ ์ฐพ์ ๋. select e2.name from employee e1, employee e2 where e1.name = 'Nora Edwardsโ and e1.departmentID = e2.departmentID; โข ์ด ์์์ employee table์ ๋ํด 2๊ฐ์ aliases ์ ์ธ ๏ pretend we have two separate tables, e1 and e2, which just happen to contain the same data. ๊ทธ๋ฐ ํ simply join them as we would any two other tables. +-------------------+ | name | +-------------------+ | Ajay Patel | | Nora Edwards | | Candy Burnett | +-------------------+ 3 rows in set (0.00 sec) โ ์ฌ๊ธฐ์ Nora๋ฅผ ๋นผ๋ ค๋ฉด ๋ค์๊ณผ ๊ฐ์ด ์์ select e2.name from employee e1, employee e2 where e1.name = 'Nora Edwardsโ and e1.departmentID = e2.departmentID and e2.name != 'Nora Edwards'; 69 Join Type์ ์ข ๋ฅ โข Basic Join โ ์์์์ Cartesian product = full join = cross join ; ๏ โข complete set of combinations.(๏ FROM ๊ณผ comma๋ก table ๋์ด) โ Join์ ์กฐ๊ฑด๋ฌธ์ ๋ถ์ฌ์ ๊ฒฐ๊ณผ๋ฅผ ํ์ ์ํค๋ ๊ฒ = equijoin โข (์: employee.departmentID = department.departmentID) โ Consider our original query: select employee.name, department.name from employee, department where employee.departmentID = department.departmentID; โ Optionally, comma๋์ keyword JOIN์ ์ฌ์ฉ ๊ฐ๋ฅ select employee.name, department.name from employee join department where employee.departmentID = department.departmentID; โ JOIN๋์ CROSS JOIN or INNER JOIN ์ฌ์ฉ๊ฐ๋ฅ. โข ์ด๋ค join ์ํ ์ MySQL looks at the tables we are joining and tries to work out the most efficient way to join them together, rather than necessarily joining the tables in the order we have listed. ๊ฐํน ์ด๋ฌํ query optimization์ด ์๋๋๋ก ๋์ง ์๋ ๊ฒฝ์ฐ๋ ์๋ค. โข If you want to override the optimizer and force to join tables70in the order in which you list them, replace JOIN with STRAIGHT JOIN. โข Understanding LEFT and RIGHT Joins โ ์์ equijoin์ ๊ฒฝ์ฐ JOIN, CROSS JOIN, INNER JOIN, or STRAIGHT JOIN์ ์ฌ์ฉ. โ ์: <<ํ table์๋ ์๋๋ฐ ๋ค๋ฅธ table์๋ ํด๋น record๊ฐ ์๋ row๋ฅผ ์ฐพ์>> โ find employees who have not yet worked on any outside assignments! select employee.name from employee left join assignment on employee.employeeID = assignment.employeeID where clientID is null; ๏จ +-------------------+ | name | +-------------------+ | Ajay Patel | | Candy Burnett | | Ben Smith | +-------------------+ 3 rows in set (0.49 sec) โ left join โข take the left-hand table in the join (์ฌ๊ธฐ์๋ employee) and try to match it to rows in the right-hand table. (Join์์์ ์ผ์ชฝ table์ ์ค๋ฅธ ์ชฝ table์ match์ํด. ) โข ๏ Right table์ matching๋๋ row๊ฐ ์๋ left table์ ๊ฐ๊ฐ์ row์ ๋ํด์๋ LEFT JOIN substitutes a row of NULL values. (๋ฐ๋ผ์ NULL key value ๋ฅผ ๊ฒ์ํ๋ฉด right table์ matching row๊ฐ ์๋ left table์ row๋ฅผ ์ฐพ์ ์ ์๋ค.) ์ฆ, โdummy rowโ๋ฅผ ์์ฑ ์ํด. (The clientID is a key field, so this should never occur in the assignment table.) โข ์์ ์์์: When an employee has no matching row in the assignment table, the left join will make up a "dummy row" consisting of all NULLs. ๏ find these dummy rows by looking for employees who have worked on an assignment for which clientID is NULL. 71 โ ์ด ์์์ RIGHT JOIN์ ์ด์ฉํ ์๋ ์๋ค. (uses the right table as a base and fills any missing rows from the left table with NULLs.) Writing Subqueries โข (๊ฐ์) โ Subquery = a query within a query = nested queries = subselect โ ์ ๊ธฐ๋ฅ์ ์์ง๋ง (๋ณต์กํ set of joins๋์ ์ฌ์ฉ๋์ด์) readability ๊ฐ์ . โข Using Derived Table Subqueries โ list a query in the FROM clause of another query. ๏ create a temporary table and add it to the query. ์: select employeeID, name from employee where job='Programmer'; โ ์ด๊ฒ์ ๋ค์ ๊ฒฝ์ฐ์ ํ์ฉ ๊ฐ๋ฅํ๋ค. select programmer.name from (select employeeID, name from employee where job='Programmer') as programmer, assignment where programmer.employeeID = assignment.employeeID; ๏จ +-------------------+ | name | +-------------------+ | Nora Edwards | +-------------------+ 1 row in set (0.01 sec) 72 โข Using Single-Value Subqueries select max(hours) from assignment; โ ์ด๊ฒ์ ๋ค์ ๊ฒฝ์ฐ์ ํ์ฉ select e.employeeID, e.name from employee e, assignment a where e.employeeID = a.employeeID and a.hours = (select max(hours) from assignment); ๏จ +-----------------+------------------+ | employeeID | name | +-----------------+------------------+ | 7513 | Nora Edwards | +-----------------+------------------+ 1 row in set (0.42 sec) โข Subqueries๊ฐ single value๊ฐ ์๋ row๋ฅผ ์ฐ์ถํ ์๋ ์๋ค. 73 โข Boolean Expression Subqueries โ (์ฉ๋) check our query against some special functions that return a Boolean expression. (์:IN, EXISTS, (grouped together) ALL, ANY, and SOME.) ์: select name from employee where employeeID not in (select employeeID from assignment); โ ์์์ LEFT JOINํ์ฉ๊ณผ ๊ฐ์ ํจ๊ณผ (๊ฐ์ ๊ฒฐ๊ณผ ์๋ต) โ ๋ค๋ฅธ ์: select name from employee where employeeID not in (6651, 1234); 74 โ EXISTS keyword (IN ๊ณผ๋ ๋ฌ๋ฆฌ ์ฌ์ฉ) โข use data from the outer query in the subquery. = a correlated subquery. โข ์ (outside assignment์ ๊ทผ๋ฌดํ ์ ์ด ์๋ employee๋ฅผ ์ฐพ๊ณ ์ ํจ) select e.name, e.employeeID from employee e where not exists (select * from assignment where employeeID = e.employeeID); โ Subquery์์, โฆ โข e.employeeID comes from the outer query. For each row in the employee table, we check the results of the subquery, and if there is no matching row (WHERE NOT EXISTS), we add the employee's details to the result set. โ ๊ฐ์ ๊ฒฐ๊ณผ๋ฅผ ์์์ LEFT JOIN์ ์ด์ฉํ ์๋ ์๋ค. (์คํ๋ ค ๋ ํจ์จ์ ) +---------------+------------------+ | name | employeeID | +---------------+------------------+ | Ajay Patel | 6651 | โฆ +----------------+-----------------+ 3 rows in set (0.00 sec) โ ALL, ANY, and SOME keywords โข Subquery์ ๊ฒฐ๊ณผ๋ฅผ ๋น๊ต (์: Nora Edwards, hardest working programmer, wants to establish that nobody works longer hours than the programmers.) select e.name from employee e, assignment a where e.employeeID = a.employeeID and a.hours > all (select a.hours from assignment a, employee e where e.employeeID = a.employeeID and e.job='Programmer'); 75 Using SELECT Statement Options SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY] [DISTINCT | DISTINCTROW | ALL] select_expression,... [INTO {OUTFILE | DUMPFILE} 'file_name' export_options] [FROM table_references [WHERE where_definition] [GROUP BY {unsigned_integer | col_name | formula} [ASC | DESC], ...] [HAVING where_definition] [ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC] ,...] [LIMIT [offset,] rows | rows OFFSET offset] [PROCEDURE procedure_name(argument_list)] [FOR UPDATE | LOCK IN SHARE MODE]] โข โข STRAIGHT JOIN ; force query optimizer to join the tables in the order specified. (=extension to ANSI SQL) SQL_SMALL_RESULT, SQL_BIG_RESULT, SQL_BUFFER_RESULT options ; optimization ์ฉ โ โ โข โข SQL_CACHE and SQL_NOCACHE ; ๊ฒฐ๊ณผ์น๋ฅผ cache ์ฒ๋ฆฌํ ๊ฒ์ธ์ง์ ์ง์ . (extension to ANSI SQL.) ?? SQL_CALC_FOUND_ROWS ; (LIMIT clause์ ํจ๊ป ์ฌ์ฉ. ) โ โข โข โข โข โข โข SQL_SMALL_RESULT and SQL_BIG_RESULT; tells MySQL that you expect the result set to have either few rows or a large number of them. SQL_BUFFER_RESULT; put the result set into a temporary table. (๊ฒฐ๊ณผ๋ฅผ client์ ๋ณด๋ด๋๋ฐ ๋๋ฌด ๋ง์ ์๊ฐ์ด ์์๋๋ ๊ฒฝ์ฐ) (= MySQL extensions to ANSI SQL) it tells MySQL to work out how many rows would have been returned if there had been no LIMIT clause. We can then retrieve this number with select found_rows(); (another extension to ANSI SQL). In versions without it, a common task is to run a COUNT(*) query and then a SELECT with a LIMIT. HIGH PRIORITY; priority over any UPDATE statements that are waiting to use the involved tables. DISTINCTROW = DISTINCT (๋จ, ALL is the opposite (return all duplicates) and is the default option.) SELECT INTO OUTFILE ; SELECT ๋ฌธ์ ๊ฒฐ๊ณผ๋ฅผ ์ง์ ๋ file๋ก ๋ณด๋.(LOAD DATA INFILE ์ ๋ฐ๋) export_options = options in LOAD DATA INFILE (see Chapter 5 for details). PROCEDURE ; ๊ฒฐ๊ณผ๊ฐ client์ ๋ณด๋ด์ง๊ธฐ ์ ์ ์ํ๋์ด์ง procedure ์ง์ (C++) FOR UPDATE and LOCK IN SHARE MODE ; storage engine์ด page- or row-level locking์ ์ฌ์ฉํ ๋๋ง ์ํฅ. โ โ 76 ์ค์ ๋ก๋ InnoDB ์ BDB. (If you specify FOR UPDATE, you will set an exclusive lock, and if you use LOCK IN SHARE MODE, you will set a shared lock. ) 8. ๋ด์ฅํจ์์ SELECT์ ์ด์ฉ 77 โข (์ผ๋ฐ๋ก ) โฆ โ โฆ โ MySQL์์๋ any expression containing NULL will evaluate to NULL, with a few exceptions. โ SELECT ๋ฅผ basic calculator๋ก ์ฌ์ฉ๋ ๊ฐ๋ฅ. select 2+2; ๏จ +-------+ | 2+2 | +-------+ | 4 | +-------+ 1 row in set (0.42 sec) 78 Operators โข Arithmetic Operators โข Comparison Operators โ +, -, *, / (๋จ,Division by zero produces a safe NULL result.) โ ํน์ด์ (1): ์ผ๋ถ ์์ธ๋ฅผ ๋นผ๊ณ comparing anything to NULL gives a NULL result. (NULL๊ณผ NULL์ ๋น๊ต ํฌํจ): select NULL=NULL; +----------------+ | NULL=NULL | +----------------+ | NULL | +----------------+ 1 row in set (0.00 sec) โ ๋น๊ต: NULL์ด ํฌํจ๋ ๋น๊ตoperator์ฌ์ฉ ์์๋ ์ฃผ์ํ ๊ฒ select NULL IS NULL; +-------------------+ | NULL IS NULL | +-------------------+ | 1 | +-------------------+ 1 row in set (0.00 sec) โ ํน์ด์ (2) โข MySQL์์ ๋๋ถ๋ถ์ string comparisons ๋ case insensitive ์ด๋ฏ๋ก case-sensitive ํ์ ์ ๋ prefix one of them with the keyword BINARY. ์: select * from department where name='marketing'; โ select * from department where name = binary 'marketing'; ๏จ โข <๊ณ์> 79 Table 8.1. Comparison Operators Operator Meaning = Equality != or <> Inequality < Less than <= Less than or equal to > Greater than >= Greater than or equal to n BETWEEN min AND max Range testing n IN (set) Set membership. Can be used with a list of literal values or expressions or with a subquery as the set. ์: (apple, orange, pear) <=> NULL safe equal. This will return 1 (true) if we compare two NULL values n IS NULL test for a NULL value in n ISNULL(n) test for a NULL value in n 80 โข Logical Operators โ MySQL interprets any nonzero, non-null value as true. โ Logical expressions in MySQL can evaluate to 1 (true), 0 (false), or NULL. โ NULL ์ด ๊ด๋ จ๋ ๊ฒฝ์ฐ ์ผ๋ฐ์ ์ธ ์ง๋ฆฌํ (truth table)์ ๋ค๋ฅธ ๊ฒฝ์ฐ๊ฐ ์๋ค. Table 8.2. Logical Operators Operator ์ ์๋ฏธ ์ง๋ฆฌํ AND or && n && m Logical AND true&&true = true false&&anything = false All other expressions evaluate to NULL. OR or || n || m Logical OR true || anything = true NULL||false = NULL NULL||NULL = NULL false||false = false NOT or ! NOT n Logical NOT !true = false !false = true !NULL = NULL XOR n XOR m Logical exclusive OR true XOR true = false true XOR false = true false XOR true = true NULL XOR n = NULL n XOR NULL = NULL 81 Control Flow Functions โข IF (e1, e2, e3) โ If e1 ์ด true์ด๋ฉด e2๋ฅผ returnํ๊ณ otherwise, it returns e3. select name, if(job='Programmer', "nerd", "not a nerd") from employee; ๏จ +-------------------+-----------------------------------------------------+ | name | if(job='Programmer', "nerd", "not a nerd") | +------------------+------------------------------------------------------+ | Ajay Patel | nerd | โฆ +------------------+------------------------------------------------------+ 4 rows in set (0.00 sec) โข CASE โ ์: CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END select workdate, case when workdate < 2000-01-01 then "archivedโ when workdate < 2003-01-01 then "oldโ else "currentโ end from assignment; 82 โข /* Assignments from the last century are categorized as "archived", ones prior to this year are categorized as "old", and everything else is "current". */ String Functions Table 8.3. String Processing Functions Function Purpose concat(s1, s2, ...) Concatenate the strings in s1, s2, .... conv (n, original_base, new_base) Convert the number n from original_base to new_base. (It may surprise you to see this as a string function, but some bases use letters in their notations, such as hexadecimal.) length(s) Returns the length in characters of the string s. load_file(filename) Returns the contents of the file stored at filename as a string. locate(needle, haystack, position) Returns the starting position of the needle string in the haystack string. ๊ฒ์ ์์์ position๋ถํฐ. lower(s) and upper(s) Convert the string s to lowercase or uppercase. quote(s) Escapes a string s so that it is suitable for insertion into the database. This involves putting the string between single quotes and inserting a backslash. replace(target, find, replace) Returns a string based on target with all incidences of find replaced with replace. soundex(s) Returns a soundex string corresponding to s. A soundex string represents how the string sounds when pronounced. It can be easier to match soundex strings of names than names themselves. substring (s, position, length) Returns length characters from s starting at position. trim(s) Removes leading and trailing whitespace from s. ((์ฐธ๊ณ ) use ltrim() to just remove whitespace 83 from the left or rtrim() for the right.) String Comparison Functions โข Using LIKE for Wildcard Matching select * from department where name like '%research%'; /* names containing 'research'. */ +--------------------+------------------------------------+ | departmentID | name | +-------------------+-------------------------------------+ | 128 | Research and Development | +-------------------+-------------------------------------+ 1 row in set (0.04 sec) โ two kinds of wildcard matching. โข %; matches any number of characters (including zero). โ '%research%' matches all strings that have the word research in them somewhere. (case insensitive) โข underscore (_); matches any single character. โ '_at' matches the strings 'cat', 'mat', 'bat', and so on. 84 โข Using RLIKE for Regular Expression Matching โ to match on the basis of regular expressions. โข regular expression = a pattern that describes the general shape of a string. โข List of strings โ The pattern 'cat' matches 'catโ, but also 'catacomb' and 'the cat sat on the mat'. โ If we want to match only the word 'cat', then the pattern would need to be '^cat$'. The caret (^) means "anchor to the start of the string;" (=the first thing at the start of a matching string is the word 'catโ). The dollar sign ($) means "anchor to the end of the string;" (=the last thing in the string must be the word 'catโ). ๏ '^cat$' can match only the string 'cat' and nothing else. โ ๋จ, ์ค์ง ํ ๊ฐ์ wildcard ์ง์: the dot (.), that will match any single character. » '.at' matches 'cat', 'bat', 'mat' and so on ๏ specify how often characters (wildcard ํฌํจ) can appear in a string. (์:'n*' matches '', 'n', 'nn', 'nnn', โฆ) » '(cat)*โ;matches '', 'cat', 'catcat', 'catcatcat', and so on. โ '.*' ; matches any number of any charactersโbasically anything. โ (+) ; means that the character or string before it should be repeated one or more times, โ (?) ; means to match zero times or one time. โ You can also list a specific range, so, for example, '(cat)(2,4)' matches 'catcat', 'catcatcat', and 'catcatcatcat'. โข ๋ํ list sets of characters. โ '[a-z]' matches any single letter, and '[a-z]*' matches any number of letters. โข character class=predefined set. ์:[[:alnum:]] matches any alphanumeric character. โข (๋จ, MySQL uses POSIX-style regular expressions โ Perl regular expressions. โ ์: select * from department where name rlike 'an'; /* containing 'an' inside them:*/๏จ +-------------------+--------------------------+ | departmentID | name | +-------------------+--------------------------+ โฆ. 85 +-------------------+--------------------------+ 3 rows in set (0.00 sec) โข Using STRCMP() for String Comparison โ STRCMP(s1, s2) returns the following values: โข 0 if the strings are equal โข -1 if s1 is less than s2? that is, if it comes before s2 in the sort order โข 1 if s1 is greater than s2? that is, if it comes after s2 in the sort order โข ์: select strcmp('cat', 'cat'); +-----------------------+ | strcmp('cat', 'cat') | +----------------------+ | 0 | +----------------------+ 1 row in set (0.42 sec) select strcmp('cat', 'dog'); +-----------------------+ | strcmp('cat', 'dog') | +-----------------------+ | -1 | +-----------------------+ 1 row in set (0.00 sec) select strcmp('cat', 'ant'); +-----------------------+ | strcmp('cat', 'ant') | +-----------------------+ | 1 | +-----------------------+ 1 row in set (0.00 sec) โ (์ฐธ๊ณ ) sort order changes with the character set. ๏ internationalization 86 Numeric Functions Table 8.4. Numeric Functions Function Purpose abs(n) absolute value of n ceiling(n) the value of n rounded up to the nearest integer. floor(n) the value of n rounded down to the nearest integer. mod(n,m) and div divide n by m. ๋จ, div returns the integral quotient, and mod() returns the integral remainder. power(n,m) Returns n to the power of m. rand(n) Returns a random number between 0 and 1. parameter n ์ optional๋ก์ pseudorandom number ์์ฑ์ seed๋ก ์ฌ์ฉ (Giving the same n to rand will produce the same pseudorandom number.) round(n[,d]) Returns n rounded to the nearest integer. If you supply d, n will be rounded to d decimal places. sqrt(n) Returns the square root of n. 87 โ ์ฃผ์: โข mod(9,2) or 9 mod 2 or even 9 % 2 ๋ชจ๋๊ฐ ๊ฐ๋ฅํ์ง๋ง โข 9 div 2 ๋ง ๊ฐ๋ฅํ๋ค. (์: div(9, 2) ๏ a syntax error.) โ mod and div in MySQL gives the following results: mysql> select 9 mod 2; +-----------+ | 9 mod 2 | +-----------+ | 1 | +-----------+ 1 row in set (0.00 sec) select 9 div 2; +----------+ | 9 div 2 | +----------+ | 4 | +----------+ 1 row in set (0.00 sec) 88 Date and Time Functions Table 8.5 Date and Time Functions Function Purpose adddate(date, INTERVAL n type) ๋ฐ subdate(date, INTERVAL n type) ๏ add and subtract dates. Type ; SECOND, MINUTE, HOUR, DAY, MONTH, YEAR, MINUTE:SECOND (format of n should be 'm:s'), HOUR:MINUTE ('h:m'), DAY_HOUR ('d h'), YEAR_MONTH ('y-m'), HOUR_SECOND ('h:m:s'), DAY_MINUTE ('d h:m'), DAY_SECOND ('d h:m:s'). curdate(), curtime(), now() ๏ current date, time, and date and time, respectively date_format(date, format) ๋ฐ time_format(time, format) ๏ reformat dates & times to any format you like. (์) date_format(workdate, '%W %D of %M, %Y'). (๏ 'Monday 16th of June, 2003'). dayname(date) ๏ name of the day in date (for example, 'Monday'). extract(type FROM date) ๏ value of type in date. (์: YEAR ๏ return the year from date.) Type๋ adddate(), subdate()์์์ ๋์ผ unix_timestamp([date]) ๏ current Unix timestamp. (= 1970/1/1์ด๋๋ก ๋ช ์ด) ๏ If called with a date, this returns timestamp corresponding to that date. 89 โ ์: start from the 1st of January 1999 and add 1 year and 6 months to it: select adddate("1999-01-01", INTERVAL "1-6" YEAR_MONTH); ๏จ +----------------------------------------------------------------------------+ | adddate("1999-01-01", INTERVAL "1-6" YEAR_MONTH) | +----------------------------------------------------------------------------+ | 2000-07-01 | +----------------------------------------------------------------------------+ 1 row in set (0.41 sec) โ Unix timestamps are not humanly readable, but they are very compatible with the APIs that come with other programming languages. (์: date() function built into PHP) โ unix_timestamp() function๊ณผ ๋์ผํ query select unix_timestamp(adddate("1999-01-01", INTERVAL "1-6" YEAR_MONTH)); +------------------------------------------------------------------------------------------+ | unix_timestamp(adddate("1999-01-01", INTERVAL "1-6" YEAR_MONTH)) | +------------------------------------------------------------------------------------------+ | 962373600 | +------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec) 90 Cast Functions โข ์ค์ง 2๊ฐ์ cast ํจ์: cast() ์ convert(). โ = typecasting (=ํ๋์ type (์: signed integer)์์ ๋ค๋ฅธ type(์: char)์ผ๋ก ๋ณํ (convert)) /* Syntax๋ ์ฝ๊ฐ ๋ค๋ฅด์ง๋ง ๋์ผํ ์์ .*/ โ Prototypes: โข cast(expression AS type) โข convert(expression, type) /* ANSI compliant, */ /* ODBC compliant.*/ โ Valid types: BINARY, CHAR, DATE, DATETIME, SIGNED (INTEGER), UNSIGNED (INTEGER). โ MySQL์์๋ ๋๋ถ๋ถ์ casting์ด ์๋์ ์ผ๋ก ์คํ๋จ. โข ์; string ํจ์์ ์ซ์๋ฅผ ์ ๋ ฅํ๋ฉด ๏ ์๋์ผ๋ก string์ผ๋ก cast ๋จ. 91 Other Functions Table 8.6. Miscellaneous Functions Function Purpose benchmark(count, expression) Evaluates expression count times. Always returns zeroโthe point of this function is to time execution and look at the execution time at the bottom of the result set. encrypt(s[,salt]) Encrypts s using a Unix crypt system call. The salt string is an optional two-character string. If crypt is not available on your system (for example, Windows), this function will return NULL. found_rows() Returns the number of rows that would have been returned by the last query if no limit clause was used. (SELECT๋ฌธ์์ SQL_CALC_FOUND_ROWS ๊ฐ ๋ช ์๋์์ ๋๋ง ์ ํจ) as in Ch 7. last_insert_id() Returns the last automatically generated AUTO_INCREMENT value. ํ table์ row insertํ ํ ๊ทธ row์ id๋ฅผ ๋ค๋ฅธ table์ foreign key ๋ก์ insertํ๋ ค๋ ๊ฒฝ์ฐ์ ์ ์ฉ. md5(s) Returns the 128-bit MD5 hash of string s. username ๊ณผ password๋ฅผ ์ ์ฅํ๋ ์์ฉ ํ๋ก๊ทธ๋จ ์์ฑ์ ์ ์ฉ. password(s) Calculates a password string for the string s. (Chapter 11) ํ๋ก๊ทธ๋จ ๋ด์์ password๋ฅผ ๋ณด๊ดํ๋ ๊ฒฝ์ฐ์ ์ด์ฉ. 92 Functions for Use with GROUP BY Clauses โ = grouping functions = aggregate functions. โ ๋ํ query์ ๊ฒฐ๊ณผ ์ ์ฒด์ ๋ํด ์ํํ ์๋ ์๋ค. (์ ์ฒด rows๋ฅผ single group์ทจ๊ธ) ์: select job, count(job) from employee group by job; select count(*) from employee; /* ๏ count the number of rows */ Table 8.7. Grouping Functions Function Purpose avg(column) Returns the average value in column. count(column) Returns the number of values in column. min(column) Returns the smallest value in column. max(column) Returns the largest value in column. std(column) Returns the standard deviation of the values in column. sum(column) Returns the sum of values in column. 93 9. MySQL Table Type์ดํด 94 ๊ธฐ์ด โข DB์ค๊ณ โ trade-offs ; (์: a transaction-safe ๏ ์๋์ ํ, ๋์คํฌ, ๋ฉ๋ชจ๋ฆฌ ๋ถ๋ด) โ ์ต์ข ๊ฒฐ์ ์ DB์ค๊ณ์ โข (์ฉ์ด) โ table types = storage engines โ This reflects โข DB์ ๋ณธ์ง์ ๋ชฉ์ ์ ๋ฐ์ดํฐ ์ ์ฅ. โข Caching, indexing, locking, and disk access๋ฑ์ ์ฒ๋ฆฌํ๋ source code๋ ํน์ ๋์ด ์๋ค. โ transaction or transaction safe โข ์: ์ํ ์๊ธ์ด์ฒด ๏ at least two SQL queriesโone to deduct, and one to add to the other. ๏จ ๋ฐ์ดํฐ๋ฒ ์ด์ค๊ฐ ์ผ๊ด์ฑ ์๋ ์ํ (a consistent state) ๋ฅผ ์ ์งํ๊ธฐ ์ํด์๋ either both happen or both fail. โ Transaction-safe tables โข ๏ a set of queries is one indivisible unit of workโa transaction. The whole transaction should complete, or the database must roll back or return to the same state it was in before the transaction started. โข MySQL์์ ์ด์ฉ ๊ฐ๋ฅํ table types๋ โ ISAM/ MyISAM/ InnoDB/ BerkeleyDB (BDB)/ MERGE/ HEAP โข ์ด ์ค์์: โ InnoDB and BerkeleyDB are transaction safe. (๋๋จธ์ง๋ X) โ ๊ฐ์ฅ ๋ง์ด ์ด์ฉ๋๋ ๊ฒ: MyISAM and InnoDB. 95 ISAM Tables โข MySQL์ ๋ด์ฅ ์ํจ ๊ฒ์ ๋จ์ง legacy support๋ฅผ ์ํ ๊ฒ โ > MyISAM table์ด ์์ ๋์ฒด -- ์ฌ๊ธฐ์ ์ธ๊ธ ์๋ต.(ver. 5.0์์ ์์ ํ ์์ด์ง ๊ฒ) โข ISAM โ ISAM table ์์ฑ (just for reference) : create table asset ( assetID int not null, description varchar(255) ) type=ISAM; โ ISAM table์ด ์กด์ฌํ์ง๋ง ์ ๊ท ๊ฐ๋ฐ์๋ ์ด์ฉX ๊ฐ๊ธ์ MyISAM์ผ๋ก ์ ํํ ๊ฒ โข MyISAM โ ์ฅ์ : โข ISAM table์ ๋น ๋ฅด์ง๋ง transaction-safe storage๋ฅผ ์ ๊ณตํ์ง ๋ชปํจ. โข Table portability. -- ๋์คํฌ ์์ Table์ (์ด๋ค ํ๋ซํผ์ด๋ ์ง) ๋ค๋ฅธ ์์คํ ์ผ๋ก load๋ ์ ์์ง๋ง ISAM table์ X โข Support for very large tables. โ OS ํ๋ ๋ด์์ ๋ฌด์ ํ โ ์ค์ ๋ก๋ ๋๋ถ๋ถ file system์ด ์ต๋ 2GB size (MERGE tabe์ ์ด์ฉํด์ ์ด ํ๋๋ฅผ ํํผ.) (Cf. ISAM tables; max 4GB.) โข ๋์คํฌ ๊ณต๊ฐ์ ๋ณด๋ค ํจ์จ์ ์ผ๋ก ์ด์ฉ ๏ space ๋ฐ fragmentation์ด ์ค์ด ๋ฌ โข Less restricted keys. - MyISAM tables ; 64 keys/table, a default max key ๊ธธ์ด= 1024 bytes. (cf. ISAM tables ; 16 keys/table, a default max key length=256 bytes.) 96 MyISAM Tables โข ๋น ๋ฅด์ง๋ง transaction-safe storage๋ ์๋. โ (MyISAM table์ ์์ฑํ๋ ์ฝ๋) create table article ( articleID int not null auto_increment primary key, title varchar(255), body text ); /* ๋๋) type=MyISAM; */ โข MyISAM table types: โข ๏ Column์ง์ ์ ๋ฐ๋ผ ์๋์ ์ผ๋ก ๊ฒฐ์ ๋จ. โ The char and numeric types ๏ ๊ณ ์ ๋ ํฌ๊ธฐ. โ The size of varchar, text, blob columns ๏ ๋ด์ฉ์ ๋ฐ๋ผ ํฌ๊ธฐ๊ฐ ๋ฌ๋ผ์ง. โ Dynamic โ Static โ compressed โข To repair or defragment a MyISAM table, โ myisamchk (command-line) ๋๋ REPAIR TABLE (MySQL ๋ช ๋ น์ด). (Ch 13) โข To defragment but not repair, โ OPTIMIZE TABLE(MySQL command) ์ด์ฉ (Ch 18) 97 โ Dynamic โข tables with variable-length rows will be created as dynamic tables. โข (cache, find, ๋๋ record์ repair ๋ฑ์ ์์ด) ๋ณด๋ค ๋ณต์กํ ๊ด๋ฆฌ๊ฐ ํ์. โ ๏ ํฌ๊ธฐ๊ฐ ๋ณํํ๊ธฐ ๋๋ฌธ์ด๊ธฐ๋ ํ์ง๋ง + fragmented๋๊ธฐ ๋๋ฌธ » Corruption์ ๊ณ ์น๊ธฐ ์ด๋ ต๋ค. » ๏ a segment of a file that has been cached by the operating system cannot be guaranteed to contain all parts of a row. โ Static โข Tables with fixed-length rows will be created as static tables โข ์ฅ์ . โ ๋ค๋ฅธ tableํ์๋ณด๋ค search๊ฐ ๋น ๋ฅด๋ค. » ๏ Index๋ฅผ ํตํด record๋ฅผ retrieveํ ๋ ๊ทธ ์์น๊ฐ ํ์ผ ์์์ ์ผ๋ก๋ถํฐ ํน์ offset์ผ๋ก ์ ํด์ง. » ๏ It is very easy to cache. » ๏ It is less likely to suffer serious corruption in the event of a crashโ the repair facility can usually recover all rows except the damaged one. โข Disadvantage โ ๋๋ถ๋ถ disk space์ ๋ญ๋น๋ฅผ ์ด๋. (๋์ column์ ๋ฐ๋ผ ๊ทธ ์ ๋๊ฐ ๋ค๋ฅด๋ค.) โ compressed โข ์ธ์์ ์ผ๋ก myisampack tool์ ์ด์ฉํ์ฌ ์์ฑ. 98 โข Compressing MyISAM Tables โ Table type์ ์๋์ผ๋ก ๊ฒฐ์ ๋์ง๋ง table compression์ ์๋์ด ์๋. ๏ myisampack. (๋จ, pure ISAM table์ ๊ฒฝ์ฐ pack_isam ์ด์ฉ) โ Compression ์ ์ข์ ๊ฒ์ฒ๋ผ ๋ค๋ฆด ์ ์์ง๋ง ์ค์ ๋ก๋ ์ผ๋ถ์๋ง ํด๋น โข ๏ compressed tables become read-only. โ Table์ alter, update, or insert data ํ ๊ฒฝ์ฐ ์ ์ฒด table์ uncompressํ๊ณ ๋ณ๊ฒฝํ ํ ๋ค์ recompress the table. โ myisampack์ ์ํ compression์ ๋ค์์ ํผํฉ ์์ฉ: โข true compression (Huffman coding) โข + a set of optimizations aimed at shrinking columns, such as โ converting types to smaller types and โ converting columns to enums. โ record ๋ณ๋ก ๊ฐ๊ฐ compress๋๋ฏ๋ก ์ค์ ๋ก overhead๋ ๊ทธ๋ฆฌ ํฌ์ง ์๋ค. This may even be counterbalanced on slow devices by the reduction in data that needs to be read from disk. 99 โข Full-Text Searching on MyISAM Tables โ ์: create a MyISAM table with a full-text index: create table article ( articleID int not null auto_increment primary key, title varchar(255), body text, fulltext (title,body)); โ ์: retrieve any records containing the word 'merger': select title from article where match (title,body) against ('merger'); โ ์: ๋ค์ ๋ฌธ์ ํฌํจํ๋ record ;'mergeโ or 'acquisitionโ or 'acquireโ or 'takeover'. select title from article where match (title,body) against ('merge acquisition acquire takeover'); โข /* ๋จ, we are matching any record that contains at least one of the words. (string or record containing every word listed ๊ฐ ์๋. ๋ค์ ๋์ด) โ 'acquireโ์ 'acquisitions' ๋ ๋ณ๊ฐ๋ก ๊ฒ์ํ ๊ฒ. ์๋ํ๋ฉด MySQL์ด stemming์ ์ง์x. โข Stemming; ์ฌ๋ฌ ๊ฐ์ ๋จ์ด์ ๋ํ ์ด๊ทผ (stem word)์ ํตํ ๊ฒ์. (์: 'acquire' is the stem of many words such as 'acquires', 'acquired', and 'acquisition'.) โ match ๋๋ ๊ฒ์ผ๋ก ๋ฐ๊ฒฌ๋ ํญ๋ชฉ์๋ relevance value๊ฐ ๋งค๊ฒจ์ง๊ณ ๊ทธ์ ๋ฐ๋ผ ์๋ sorting๋. โข You may want to see the relevance scores for records. โ ์: retrieve an unsorted list of scores for all records. Any records with a score of zero have no similarity and will not be retrieved. select title, match (title,body) against ('merge acquisition acquire takeover') as relevance from article; โข /* ๋จ, relevance ๋ keyword๊ฐ ์๋๋ผ just an alias for match(title,body) against ('merge acquisition 100 acquire takeover')*/ โ ์: retrieve article titles and scores for matched documents. select title, match (title,body) against ('merge acquisition acquire takeover') as relevance from article where match (title,body) against ('merge acquisition acquire takeover'); โ ๊ฒ์ํ ์ ์๋ ๋จ์ด:๏ ์ฑ๋ฅ๋ฌธ์ ๋ฑ โข Short words are not indexed. โ 4 characters (default) ๋ฏธ๋ง์ ๋ฌด์. For some installations, most famously Slashdot.org, this is a problem because three-letter acronyms are often an important part of the content in technical material. You can change this limit by altering the variable ft_min_word_len, but you will need to regenerate your indexes. โข Stop word = a word with no semantic value. ๋ฌธ์ฅ๊ตฌ์ฑ์๋ ์ค์ํ๋ ์ปจํ ์ธ ์์๋ ์ค์์น ์์ ๊ฒ. (์: 'the', 'and', 'then', and 'soon' ) ํ์ค์ stop word์ธ์๋ ๋ณ๋ ์ง์ ๊ฐ๋ฅ. โ ์ฐธ๊ณ :full-text indexing์ ๋ณต์กํ ์์ . ๊ท๋ชจ๊ฐ ์ปค์ง๋ฉด (์: > 1 M row) ์ฑ๋ฅ์ ํ. โ Words that are common in your data are not used when searching. โข ์: Table์ company newsletter articles for Acme PTY Ltd.์ด ํฌํจ๋๋ฉด 'Acme'๋ผ๋ ๋ง์ด ๋ฐ๋ณต๋๊ธฐ ์ฝ๋ค. If 50% or more of your records contain a word, that word is taken to have no value when calculating relevance. 101 โข Boolean Full-Text Search โ ์: match only records that contain the word 'linux' and the string "Open Source", but not the word 'desktop'. ๋ํ 'Java' ์ 'Oracleโ์ optional. ๊ทธ ๋ฆฌ๊ณ ์ด๋ record์ 'Javaโ๊ฐ ํฌํจ๋๋ฉด relevance๊ฐ ์ฌ๋ผ๊ฐ๊ณ 'Oracle' ์ด ํฌํจ๋ ๋ฉด degrade the ranking. search string ์์์ ๋จ์ด ๋๋ record์ ์์๋ ์ค์ ํ์ง ์์. select title from article where match (title,body) against ('+linux +"Open Source" -desktop Java ~Oracle' IN BOOLEAN MODE); โ Boolean mode๊ฒ์์ ๋ฐ๋์ full-text index๊ฐ ํ์์น๋ ์์ง๋ง unindexed table์ ๊ฒ์์ ๋งค์ฐ ๋ฆ์ด์ง. โ ๋ํ Boolean mode๋ก ๊ฒ์ ์์๋ ํํ ๋ํ๋๋ ๋จ์ด๋ ๋ฌด์ํ์ง ์๊ณ ๊ฒ์. ์ฆ, 50% rule does not apply. โข ์ ๋ฌธ์ article์์ Acme PTY Ltd๋ฅผ ๊ฒ์ํ๋ ๊ฒฝ์ฐ ๋ค์ ์ฒซ์งธ query๋ฌธ์์๋ ๋๋ถ๋ถ์ row๊ฐ ์ถ๋ ฅ๋์ง๋ง ๊ทธ ๋ค์์ query๋ฌธ์์๋ empty result set. select title from article where match (title,body) against ('Acme' IN BOOLEAN MODE); select title from article where match (title,body) against ('Acme'); 102 Table 9.1. Boolean Mode Search Operators Oper ator Meaning + This word is compulsory. - This word must not appear. < This word is less important. > This word is more important. () Group words together as a subexpression. ~ This word may appear, but it has a negative effect on ranking. * Wildcard suffix. ์: merge will not match merger, but merge* will match both merge and merger. May be used only at the end of a word. "" This is a phrase. Matches only exactly the same content in the same order. 103 InnoDB Tables โข ์ผ๋ฐ๋ก โ InnoDB is a fast, transaction-safe storage engine (TransactionsโCh 10) โ InnoBase Oy ์ญ์ dual-licensing. (www.innodb.com) โ ํนํ ๋๋ ๋ฐ์ดํฐ๋ฅผ ๊ณ ์์ผ๋ก transaction-safe ํ๊ฒฝ์์ ์ฒ๋ฆฌํ๋ ๊ฒฝ์ฐ ์ ์ฉ. โข ์ฌ๋ก: Slashdot (www.slashdot.org), Google (www.google.com), and Yahoo! Finance (http://finance.yahoo.com) โ ๋๋ถ๋ถ์ ๊ฒฝ์ฐ MyISAM์ด ๋ค์ ๋น ๋ฅด๋ค. โ Row-level locking. โข ๏ only the row we are using in a particular query is unavailable to other users. (BDB์ ์ธํ) ๋๋ถ๋ถ ๋ค๋ฅธ storage์์ง์ table-level locking, ์ฆ, while one process is updating a table, it is not available to other processes. โ Support for foreign keys. โ Consistent nonlocking reads in SELECTs. โข (The idea for this is borrowed from Oracle.) โข InnoDB has its own configuration options, its own directory, and its own way of storing data. โ Whereas MyISAM stores one table per file, InnoDB stores all its tables and indexes in a tablespace, which means that they may be stored over multiple files. This allows InnoDB to have very large tables that will be unaffected by any operating-system file size restrictions. โ ๋จ, MyISAM์ ๋น๊ตํ์ฌ ๋์ผ record์ ์ฅ์ ํจ์ฌ ๋ง์ disk ๊ณต๊ฐ ์ฌ์ฉ. 104 BerkeleyDB (BDB) Tables โข BDB is provided by Sleepycat software (www.sleepycat.com). โข All BDB tables must have a primary key (not that this is much of a problem because we would recommend this anyway). In fact, one will be created silently for you if you do not create one for yourself. โข ๊ทธ๋ฌ๋ ๊ทธ๋ฆฌ ๋ง์ด ์ฐ์ด์ง ์์. โ โ โ โ BDB engine์ ์ค๋ ์ ์ ๋์์ง๋ง MySQL integration์ ์ต๊ทผ. page-level locking์ด๋ฏ๋ก InnoDB๋ณด๋ค ์ฑ๋ฅ์ด ๋ค์ ๋จ์ด์ง ๋ํ ๋ง์ table์ ๋์์ ์ด์ด๋์ผ๋ฉด ์ฑ๋ฅ์ ํ. BDB tables are stored as b-trees. โข ๋น๊ต: ๋๋ถ๋ถ์ ๋ค๋ฅธ table types store their indexes as b-trees. ๏ table scanning์ด ๋ฆ์ด์ง (such as when you are retrieving all rows from the table or performing unindexed queries). โ BDB tables also take up more space on disk. โ you cannot move the stored data around on disk. ์๋ํ๋ฉด the data stored for a table includes the path to the data. โ ๋ํ be careful when backing up BDB tables to remember to back up the log files because you will be unable to restart without them. 105 MERGE Tables โข maximum file size์ ๋ํ ์ด์์ฒด์ ์ ํ๊ณ๋ฅผ ๊ทน๋ณตํ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ ์ฉ. โ Because each MyISAM table is stored in a single file, tables are limited in size by the maximum file size of the operating system. โ MERGE table = a construct that allows you to treat multiple MyISAM tables as a single table for the purpose of queries. โข ์: create a MERGE table consisting of three log tables (Listing 9.1) โข MERGE table์์๋ ๊ฐ๊ฐ์ table์ ๋ํด query ๊ฐ๋ฅ. โข ๋จ, We cannot DROP, ALTER, DELETE FROM TABLE, REPAIR, TRUNCATE, OPTIMIZE, or ANALYZE any of the component tables. You will be able to do some of these things (DELETE FROM TABLE) if the MERGE table is not currently open. You can close it with FLUSH TABLES. โ manual ์์๋ FLUSH ํ์ ์์ ์์ ์ ํ ์ ์๋ค๊ณ ํ์ง๋ง ์ค์ ๋ก๋ ์ ์๋จ (*) ์; dropping one of the component tables leads to the MERGE table also being silently dropped. If you need to make these sorts of changes, you may be better off dropping the MERGE table and re-creating it. Dropping the MERGE table does not affect the component tables or their data. โข You can compress individual tables in the MERGE with myisampack. ์ฌ๊ธฐ์์ logfile ์์์ ์ ์ฉโcompress the earlier months' log files because we are writing to only the most recent log. 106 Listing 9.1 A MERGE Table Example create database logs; use logs; create table log2003Jan (logid int auto_increment primary key, logts datetime, entry char(255)); insert into log2003Jan values (NULL, '2003-01-01', 'first jan entry'); create table log2003Feb (logid int auto_increment primary key, logts datetime, entry char(255)); insert into log2003Feb values (NULL, '2003-02-01', 'first feb entry'); create table log2003Mar (logid int auto_increment primary key, logts datetime, entry char(255)); insert into log2003Mar values (NULL, '2003-03-01', 'first mar entry'); create table logs (logid int auto_increment primary key, logts datetime, entry char(255)) type = merge union = (log2003Jan, log2003Feb, log2003Mar) insert_method = last; ๏ถ ๋์ผํ structure์ table 3๊ฐ๋ฅผ ์์ฑ (log2003Jan, โฆ) ๏ถ Logging is a common application of MERGE tables. ๏ถ ๋ฐ์ดํฐ ์ ๋ ฅ ํ MERGE table ์์ฑ, by creating logs table. (specifying that it is of type MERGE and that it is the UNION of the three tables.) ๏ถ๋งจ ๋์ INSERT_METHOD ; if we insert data into the MERGE table, it will be added to the last table in the merge, in this case log2003Mar. The other options are FIRST (insert into the first table in the list) or NO (don't allow inserts into the MERGE table). ๏ถ ๏จ a table that contains all the data in the merged tables. ๏ถ (์ค์) MERGE table์์์ primary key์ธ logid ๋ ์ผ๋ฐ์ ์ธ primary key์ ์ด์ฉ๋ฐฉ์๊ณผ๋ ๋ค๋ฅด๋ค. Usually, they must be unique, but because the MERGE table manages three sets of primary keys, there may well be more than one row with the same primary key, as in the preceding output. (run the query) select * from logs; ๏จ +-------+--------------------------+-------------------+ | logid | logts | entry | +-------+--------------------------+-------------------+ | 1 | 2003-01-01 00:00:00 | first jan entry | | 1 | 2003-02-01 00:00:00 | first feb entry | | 1 | 2003-03-01 00:00:00 | first mar entry | +-------+---------------------------+-------------------+ 3 rows in set (0.01 sec) 107 HEAP Tables โข = extremely fast tables that are stored wholly in memory. ๏ hashed indexing scheme ์ด์ฉ โข ์ฅ๋จ์ โ ๋จ์ ; ์ ์๋ฌธ์ ๋ฐ์ ์ your HEAP data is gone forever. โ ์ฅ์ : temporary table ์ ์ฅ์ ์ ํฉ. โข You can create a HEAP table like this: โข โข โข โข create table testHeap (id int not null primary key, data char(100)) type=heap max_rows = 100; โ ์ด ์์์์ฒ๋ผ max number of rows๋ฅผ limitํ๋ ๊ฒ์ด ์ข๋ค. ๏ HEAP table์ด ์ปค์ง๋ฉด ๊ณง๋ฐ๋ก ๋ฉ๋ชจ๋ฆฌ ๋ถ์กฑ๋ฌธ์ . The number of rows can also be limited by the configuration directive max_heap_table_size. โข HEAP tables have a few limitations: โ โ โ โ AUTO_INCREMENT ์ง์x BLOB or TEXT type ์ง์ x HEAP tables cannot use the leftmost prefix of an index to find rows. Indexes will be used only to find rows with queries that use the = or <=> operators in the search clause. 108 10. InnoDB Table์ ํตํ Transaction ์ด์ฉ 109 Transaction์ด๋? โข A transaction = a sequence of related instructions that must be treated as one indivisible unit. โ (atomicity) A transaction cannot be broken down into partsโIt all gets processed (done) or it all gets ignored (undone). โ ์: ์ํ ๊ณ์ข๊ด๋ฆฌ (bank account) create table account ( number int not null auto_increment primary key, balance float ) type = InnoDB; โข (๊ทธ๋ฐ ํ) insert into account (balance) values (0.0); insert into account (balance) values (1000.0); insert into account (balance) values (2000.0); โข (๊ฒฐ๊ณผ) +------------+-----------+ | number | balance | +------------+-----------+ | 1 | 0 | | 2 | 1000 | | 3 | 2000 | 110 โ (๋จ์ํ ์ฌ๋ก: deposit $500 into account 2) # first check balance select balance from account where number = 2; # query gives us a result of $1000 # now store updated balance update account set balance = 1500 where number = 2; โ These queries are related. They need to be run together. โข ๋ง์ฝ ์์ก์กฐํ์ update ์ฌ์ด์ balance๋ฅผ ๋ค๋ฅธ ์ฌ๋์ด updateํ๋ค๋ฉด ๋ฌธ์ ! โข IF query๋ฅผ ํตํด $500์ ์๊ธํ๊ณ ๋ค๋ฅธ ๊ณ ๊ฐ์ด $100์ ์๊ธํ๋ ค ํ๋ค๋ฉด THEN ์์ก ๊ฒฐ๊ณผ์น๋ $1100 ๋ ๋ ์ ์๊ณ $1500๋ ๋ ์ ์๋ค. # first check balance select balance from account where number = 2; # query gives us a result of $1000 # now store updated balance update account set balance = 1100 where number = 2; โ ๋จ, ์ด ๊ฒฝ์ฐ์๋ ๋ฌธ์ ๊ฐ ์ฝ๊ฒ ํด๊ฒฐ๋ ์ ์๋ค.๏ Make our updates relative rather than absolute will make them into single, indivisible units and will solve the problem. โ ๋ค์ query๋ (๋ค๋ฅธ query๊ฐ ๋์ ์คํ๋๋์ง ๊ด๊ณ์์ด) ์ด์ฉํ ์ ์๋ค. update account set balance = balance + 500 where number = 2; โ A single update statement in MySQL is always atomic. It cannot be interrupted by another query or half succeed. It will complete or will completely fail on an error. 111 โ (๋ณต์กํ scenario) transfer $1000 from account 2 to account 1: update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; โ 2๊ฐ์ query๊ฐ ํจ๊ป ์ํ๋์ด์ผ ํ๋ค. ๏ ๊ฑฐ๋ ์ ํ์ ์ด ๊ธ์ก(total amount)๋ ๋์ผ. ๋์ค์ power failure๊ฐ ๋ฐ์ ์ data๊ฐ inconsistent! ๏จ collapse queries into one SQL statement! update account as source, account as dest set source.balance = source.balance ?1000, dest.balance = dest.balance + 1000 where source.number = 2 and dest.number = 1; โ account table์ ๋ํ 2๊ฐ์ aliases (source ๋ฐ dest)๋ฅผ ํตํด ํ๋์ atomic update๊ฐ either succeed or failํ๋๋ก ํ์๋ค. Readability๊ฐ ๋ฌธ์ ์ผ ๋ฟ. ๊ทธ๋ฌ๋ ๋ง์ ๊ฒฝ์ฐ ๋ชจ๋ ๊ด๋ จ query๋ค์ ์ด์ฒ๋ผ collapse์ํค๋ ๊ฒ์ด ๋ถ๊ฐ๋ฅํ๋ค. โ (solution) use MySQL's transaction syntax๋ฅผ ํตํด ์ฌ๋ฌ ๋ฌธ์ฅ์ ํ๋์ transaction (=a related, indivisible set). ์ผ๋ก ํ์ start transaction; update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; commit; โ (transaction์ ํน์ง) โข they are not visible to other sessions until they are complete and committed. No other thread can read inconsistent data from the table(s) while you are in the process of updating it. โข partially performed transactions can be undone. ๏ roll back the transaction before we have committed it ๏ changes made by queries that are part of the transaction will be undone. โข (์์ ์์์ SELECT ๋ฌธ์ ํตํด ์๊ณ ์ด์์ ์ธ์ถ์ ๋ชปํ๊ฒ ํ๋ฉด ๏ ROLLBACK๋ฅผ ํตํด cancel ๊ฐ๋ฅ) start transaction; update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; select balance from account where number = 2; # select tells us that account #2 has a negative balance! # we'd better abort rollback; โ Calling ROLLBACK aborts the transaction and undoes any changes made. A transaction that was rolled back instead of committed leaves no trace in the data. Because partial results were never visible to other sessions, it is exactly as though it never happened. 112 Using Transactions in MySQL โ START TRANSACTION is synonymous with BEGIN or BEGIN WORK. โข ๋ค๋ฅธ DB ์ฌ์ฉ ๋ฑ์ ๋ฐ๋ผ ๋ฌ๋ผ์ง์ง๋ง START TRANSACTION ๊ฐ SQL-99 syntax์ด๋ฏ๋ก ๊ถ์ฅ. โข Setting the Autocommit Mode โ ๋ณดํต ๋ ์ด๋ฏธ autocommit mode๋ก ์ํโ๊ฐ query๋ ์ค์ ํ๋์ isolated transaction. (๋ชจ๋ query์ ๋ํด ์๋์ผ๋ก START TRANSACTION ๋ฐ COMMIT๊ฐ ์ ์ฉ๋ ํจ๊ณผ) update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; โ == start transaction; update account set balance = balance - 1000 where number = 2; commit; start transaction; update account set balance = balance + 1000 where number = 1;commit; โ Note that if you manually type start transaction; /* ๏ nothing will be committed until */ commit; โ To disable the autocommit behavior using the SET command: set autocommit=0; โข ๏ ์ด ๊ฒฝ์ฐ์๋ START TRANSACTION ์ ์ด์ฉํ ํ์๊ฐ ์๋ค. โข (์ค์) ๋จ, ์ฃผ๊ธฐ์ ์ผ๋ก COMMIT ๋ฅผ ์ํํ์ฌ ๋ฐ์ดํฐ๋ฒ ์ด์ค ๋ณ๊ฒฝ์ฌํญ์ ์ ์ฉํด ์ค ๊ฒ. โ To put MySQL back into autocommit mode: set autocommit=1; โ The autocommit variable is local to a single session โข changing the mode will affect only queries run from your session and only for as long 113 as your session is connected. โข autocommit ๊ฐ on์ด๋ off์ด๋ ์๊ด์์ด ๊ฐํน ๋ณ๊ฒฝ์ฌํญ์ด ์๋์ผ๋ก ์ ์ฉ๋๋ ๊ฒฝ์ฐ๊ฐ ์๋ค. ์ฆ, MyISAM๊ณผ ๊ฐ์ non-transaction-safe table type์ ์ด์ฉํ๋ ๊ฒฝ์ฐ ๋ชจ๋ ๋ณ๊ฒฝ์ฌํญ์ (autocommit setting ์ ์๊ด์์ด) ์ฆ๊ฐ (immediately) commit๋๋ค. โ You can happily group your statements with START TRANSACTION and COMMIT; it is just that this will have no effect on the nontransaction-safe tables. โ ์ฌ์ง์ด ROLLBACK์ ํธ์ถ(call)ํ ์๋ ์๋ค. ๏ ์คํ์ค๋ฅ๊ฐ ๋์ง๋ ์๊ณ ๋จ์ง ์๋ฌด๋ฐ ํจ๊ณผ๊ฐ ์์ ๋ฟ. โ ๊ฐ๊ฐ ๋ค๋ฅธ table type์ ๊ฐ์ง ์๋ฒ์ dump file์ reloadํ๊ฑฐ๋ code test ํ๋ ๊ฒฝ์ฐ ์ ์ฉ. โข For transaction-safe tables, there are actions (other than typing COMMIT) that will automatically trigger a COMMIT. Requesting a lock will implicitly commit any outstanding queries. 114 Locks์ ์ด์ฉ โข Table์ manually lock and unlockํด๋ transaction์ ํจ๊ณผ๋ฅผ ๊ฑฐ๋ ์ ์๋ค. lock tables account write; select balance from account where number = 2; update account set balance = 1500 where number = 2; unlock tables; โ ๋จ, ์ผ๋จ table์ lockํ๋ฉด ๊ฐ๋ฅํ ๋นจ๋ฆฌ unlockํด์ผ ๋ค๋ฅธ thread์ ๋ํ impact๋ฅผ ์ค์ผ ์ ์๋ค. ๋ฐ๋ผ์ Request all the locks you need at once! โข ์์์ ๋ฌ๋ฆฌ ์ฌ๋ฌ ํ ์ด๋ธ์ ์ด์ฉํ๋ฉด์ lock์ด ํ์ํ๋ฉด ํจ๊ป ํธ์ถ: lock tables account write, account as a read, othertable low_priority write; โ LOCK TABLES๋ฅผ ํธ์ถํ๋ฉด ๊ธฐ์กด์ ๋ชจ๋ lock์ ํด์ (release). โข ๏ If you attempt to collect the locks you need over multiple statements, you will release all the early ones and will only actually hold the locks requested in the final statement. 115 โข (Lock์ ์ฃผ๋ ์ ํ:= read and write.) โ ๊ธฐ๋ก์ ์ํด table accessํ ๋ write lockํ๋ฉด ๋ค๋ฅธ ์ด๋ค thread๋ read/write๊ฐ ๋ถ๊ฐ๋ฅ (until you release it). โ A read lock is less extreme. ๋จ์ง table read๋ง ํ๋ ค๋ ๊ฒฝ์ฐ ๋ค๋ฅธ thread๊ฐ ๋์ ์ readํ๋ ๊ฒ์ ์๊ด ์๋ค. (๋จ์ง lock์ ๊ฑด ๋์ ๋ค๋ฅธ thread์ write๋ง ๊ธ์ง) โข write lock์์ low_priority๋ก ํ์; ๋๊ตฌ์๊ฒ lock์ ์ฐ์ ์์๋ฅผ ์ค ๊ฒ์ธ๊ฐ์ ๋ํ policy ๊ฐ ํ์. โข MySQL์ ๋ณดํต write lock request์ ๋ํด read lock๋ณด๋ค ์ฐ์ ๊ถ (priority)์ ์ฃผ์ด์ ๊ธฐ์กด ์ ์ฅ๋ ๋ฐ์ดํฐ์ update๊ฐ ๊ฐ๊ธ์ ๋นจ๋ฆฌ ์ด๋ฃจ์ด์ง๋๋ก ํจ. ๋ง์ฝ ๋ค๋ฅธ ๋ฐฉ์์ ์ํ๋ค๋ฉด you can request a low-priority write lock (์์ ์์์์ other table). ๋จ, ์ฃผ์: Lock์ requestํ ๋๋ง๋ค ์ ์ waitํด์ผ ํ๋ค. ๋ํ low-priority lock will be granted only if there are no other threads requesting read or write locks on that table. It is possible on a busy server that this might never happen. โ ๊ฐํน lock์ manually controlํด์ผ ํ๋ ๊ฒฝ์ฐ โข If you have an application that requires very high performance but needs transaction-like behavior only occasionally, it might be worth using a fast nontransaction-safe table type and using locks to solve your transaction issue. โ ๋ํ LOCK TABLES์ callํ๋ ๊ฒฝ์ฐ โข MySQL's data file์ ์ง์ ์์ ํ๋ ๊ฒฝ์ฐ. ์: Backup ์ ํ์ธ!: โdisk files stayed consistent and unmodified while backing up.โ ์ฆ, you would need to lock them. โ (์ค์) ๋ค๋ฅธ ์ฌ์ฉ์๋ฅผ ์ํด lock์ ์ฌ์ฉ ํ์๋ ๊ฐ๋ฅํ ๋นจ๋ฆฌ release lock. Some tasks you may lock while performing, such as reindexing or backing up large files, can take significant amounts of time. 116 InnoDB์ Transaction Model โข ACID Compliance โ Atomicity; transactions are atomic and indivisible. โ Consistency; operations transform the database from one valid state to another. ์ฆ, no intermediate stages where the data is inconsistent. โ Isolation; transactions do not affect each other while they are running. Each transaction should be able to view the world as though it is the only one reading and altering things. โข ์ค์ ์์๋ ์ด๋ ค์ด ์ํฉ์ด๋ฏ๋ก lock์ ํตํด ์ด๋ฌํ illusion์ ๋ง๋ค์ด ๋. โ Database์ option์ ๋ฐ๋ผ different levels of isolation. โ Durability; ์ผ๋จ transaction์ด commit๋๋ฉด ๊ทธ ํจ๊ณผ(effect)๋ permanent ํ๋ค. โข ๋๊ฐ ๋จ์ํ์ง๋ง ๋ณต์กํ DBMS (locking ๋ฐ multiversioning์ ํตํด concurrent multiuser access๋ฅผ ๋ณด์ฅํ๊ณ caching์ ํตํด ์ฑ๋ฅํฅ์์ ์ถ๊ตฌ)๊ฒฝ์ฐ ์ ์ฌ์ ํญํ! โข ๋ํ durability implies recoverability in the event of a failure ๏ we should be able to combine a backup and a log to bring the database back to its precrash state and perhaps process transactions that had been logged but not yet executed or committed. โ InnoDB tables (or BerkeleyDB tables)์ ์ด์ฉํ๋ฉด โข MySQL is ACID compliant. (cf. MyISAM table์ด์ฉํ๋ ๊ฒฝ์ฐ x) โข You can choose the level of isolation that transactions have from one 117 another. The binary log and repair tools provide durability. โข Transaction Isolation โ InnoDB table์ 4๊ฐ์ง transaction isolation level์ ๊ฐ์ง. (โstrong๏ weakโ์์) โข โข โข โข โข Serializable Repeatable read Read committed Read uncommitted /* trade-off between robustness and performance. */ โ Serializable isolation โข is the ideal from a purity and robustness angle. โข ๏ Reads and writes on the database appear to be happening in a sequence, with changes from a write being completely recorded before the next read starts. โข Transaction์ด ํญ์ noninterleaved sequence๋ก ์ํ๋ ํ์๋ ์๋ค. (๋ง์ ๊ฒฝ ์ฐ ์๋ก interfereํ์ง ์์ผ๋ฏ๋ก) โข ๊ทธ๋ฌ๋ clash๊ฐ ๋ฐ์ํ๋ฉด noninterleaved sequence๋ก ์ํํด์ผ ํ๋ค. ์ด ๊ฒฝ์ฐ locking and waiting + (์ด๋ค transaction๋ค์ด interfereํ๋์ง์ ์กฐํฉ์ ๋ํ) overhead of predicting ๏จ serializable isolation ์ ๊ฐ์ฅ ์ฑ๋ฅ์ด ๋๋ ค์ง. ์ด๋ฌ ํ mode ํ์ ์ ๋ค์ ๋ช ๋ น์ด ์ํ: โข /*set transaction isolation level serializable; */ โ Repeatable read (์ดํ ๋ค์ ํ์ด์ง) โ Read committed โ Read uncommitted 118 โ repeatable read. โข InnoDB์์์ default level. ์ฌ๊ธฐ์๋ each transaction gets to work in an isolated version of the table where each row remains as it was when the transaction started. Reading a row is guaranteed to be repeatable. โข If you call select * from account where number=1; at the start of the transaction and perform the same query later in the transaction, you will get the same results both times. You can, however, get what are called phantom reads. It is possible that another transaction which commits before yours is adding new rows to the table. If you perform the same query with a condition twice, such as select * from account where balance>1000; โข it is possible that you will get new rowsโphantom rowsโthe second time. ์ค์ ๋ก ๋ phantom read๋ ๋งค์ฐ ๋๋ฌผ๋ค. InnoDB์์๋ ์ด๋ฌํ ๋ฌธ์ ํด๊ฒฐ์ (์ด๋ฌํ ์กฐ๊ฑด์ ์ ์ฉ ํ๋ column์ด index๋์๋ค๋ฉด) next key locking ๋ผ๋ algorithm ์ฌ์ฉ. โข ๋ํ InnoDB์ row-level locking. ๏ โฆ As well as locking the rows used, next key locking also locks the gaps between rows found in the index. Because phantom reads are addressed in this way, few systems really need to be put in serialized isolation mode. โ read committed โข your transactions are no longer very isolated. If you perform a query and repeat it later in the same transaction, you will get different results the second time if another transaction has modified the data in the meantime and committed. โข ์ด๋ฅผ ์ํด์๋: set transaction isolation level read committed; โ read uncommitted, โข ์ฌ๊ธฐ์๋ it is distinctly arguable not only that your transactions are no longer isolated, consistent, and therefore ACID compliant, but that you no longer really have transactions. In this mode, it is possible for transactions to read changes that other transactions have made before the changes have been committed. (=a dirty read). You would tolerate this only in fairly unusual circumstances, such as at a time when you know all active threads will be reading or writing, but not 119 both. read uncommitted mode๋ฅผ ์ํด์๋: set transaction isolation level read uncommitted; Table 10.1. Transaction Isolation Level Characteristics Dirty Read Nonrepeatable Read Phantom Read Read Uncommitted Possible Possible Possible Read Committed Not possible Possible Possible Repeatable Read Not possible Not possible Possible (but unlikely) Serializable Not possible Not possible Not possible 120 Part V: MySQL ๊ด๋ฆฌ 11 12 13 14 15 16 Managing User Privileges Configuring MySQL Administering Your Database Backup and Disaster Recovery Securing Your MySQL Installation Replicating Your Database 121 11. User Privileges์ ๊ด๋ฆฌ โข Creating user accounts with GRANT and REVOKE โข Privilege levels โข Understanding the privilege tables 122 Creating User Accounts with GRANT and REVOKE โข Granting Privileges โ to create user accounts and give users access to databases, tables, and functions. grant usage /* usage= log in๋ง ๊ฐ๋ฅ */ on * to luke@localhost identified by 'password'; โ ์ผ๋ฐํ: GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...] ON {tbl_name | * | *.* | db_name.*} TO user_name [IDENTIFIED BY [PASSWORD] 'password'] [, user_name [IDENTIFIED BY 'password'] ...] [REQUIRE NONE | [{SSL| X509}] [CIPHER cipher [AND]] [ISSUER issuer [AND]] [SUBJECT subject]] [WITH [GRANT OPTION | MAX_QUERIES_PER_HOUR # | MAX_UPDATES_PER_HOUR # | MAX_CONNECTIONS_PER_HOUR #]] โข * ; ํ์ฌ ์ ํ๋ database์ ์ ์ฉ, ์ ํ๋ database๊ฐ ์์ ๋์๋ =*.* โข TO ; ๋์์ ์ง์ . Log in ๋ host๋ ๊ฐ๋ฅ ; ์: fred@localhost. โฆ (Username; ์ต๋ 16 ๋ฌธ์) โข IDENTIFIED BY; password ์ค์ (์ ๊ท ์ฌ์ฉ์ ๋๋ ๊ธฐ์กด user). โข ์ฌ์ฉ์๊ฐ Password ๋ณ๊ฒฝ ์์ ; set password = password('newpassword'); โข ๊ด๋ฆฌ์๊ฐ ์ฌ์ฉ์ password๋ณ๊ฒฝ; set password for fred@localhost = password(โnewpasswordโ) /*๏ mysql์ด๋ผ๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ access๊ถํ์ ๊ฐ์ ธ์ผ ํจ */ โข WITH GRANT OPTION ; a special privilege that allows the user to grant privileges. โข WITH ; 1์๊ฐ ๋ด์ ์๋ํ ์ ์๋ query, update, connection ํ์ (default= 0 =no limitation.) โข REQUIRE; secure connection์ด ์์ด์ผ ์ฌ์ฉ์๊ฐ ์ฐ๊ฒฐํ ์ ์๋๋ก ํจ. (ํด๋น configuration123 ํ์) Privilege Levels Table 11.1 User-Level Privileges Privilege Meaning (์ฌ์ฉ์๊ฐ โฆ์ ํ ์ ์์) CREATE Create tables CREATE TEMPORARY TABLES Create temporary tables DELETE Delete rows EXECUTE Execute procedures INDEX Create indexes INSERT Insert rows LOCK TABLES Lock tables SELECT Select rows SHOW DATABASES โSHOW DATABASESโ ํตํด available DB list ์ถ๋ ฅ UPDATE Update rows USAGE Users can log in, but cannot do anything else 124 Table 11.2 Administrator-Level Privileges Privilege Meaning ALL User has all the privileges except WITH GRANT OPTION ALTER User can alter tables. ์ผ๋ถ power user์๊ฒ ๋ถ์ฌํ ๋๋ ์ฃผ์ํ ๊ฒ privilege table์ ๋ณ๊ฒฝํ๋๋ฐ ์ฌ์ฉ๋ ์๋ ์์ DROP User can drop tables. Only to the trusted users! FILE User can load data from a file. Only to the trusted users! (์ฃผ์) ์ฌ์ฉ์๊ฐ arbitrary file (์:/etc/passwd)์ loadํ์ง ์๋๋ก ์ ์ PROCESS MySQL ์์ ์ํ๋๋ ๋ชจ๋ process์ list๋ฅผ ์ถ๋ ฅ RELOAD User can use the FLUSH statement. REPLICATION CLIENT User can check where the masters and slaves are. REPLICATION SLAVE slave์์์ special replication user ๋ฅผ ์ํ ํน์ํ privilege. SHUTDOWN User can run mysqladmin shutdown. SUPER User can connect even if MySQL has its maximum number of connections and can execute the commands CHANGE MASTER, KILL (thread), mysqladmin debug, PURGE MASTER LOGS, and SET GLOBAL. WITH GRANT OPTION User can pass on any privileges he has. REFERENCES Future use๋ฅผ ์ํด ์์ฝ๋จ 125 ๏ Evaluating Privileges โข 4 sets of privileges are granted with GRANT statement: โ Global privileges ; ๋ชจ๋ database์ ์ ์ฉ. grant all on *.* to fred; โ Database privileges ; ํน์ database์ ์ ์ฉ. grant all on employee.* to fred; โ Table privileges ; ํน์ table์ ์ ์ฉ. grant select on department to fred; โ Column privileges apply to a single column. grant select (employeeID) on employee to fred; โข ํน์ ์ฌ์ฉ์์ privilege ๊ฒฐ์ ์๋ โ ๊ทธ ์ฌ์ฉ์์ <<global privileges + database privileges + table privileges + column privileges>> ๋ฅผ ORed together. 126 Using the REVOKE Statement โข = GRANT์ ๋ฐ๋. (= privilege๋ฅผ ๋นผ์์) โ ์: revoke all on employee.* from fred; โข ์ผ๋ฐํ: REVOKE priv_type [(column_list)] [(column_list)] ...] ON {tbl_name | * | *.* | db_name.*} FROM user_name [, user_name ...] [, priv_type 127 Privilege Tables โข GRANT ๋ฐ REVOKE์ ๊ฒฐ๊ณผ๋ mysql์ด๋ผ๋ database ์ ์ ์ฅ. ์ด๋ค ๋ช ๋ น์ด๋ฅผ ์ฌ์ฉ ๋์ ์ง์ ์ด database๋ฅผ ์์ ๋ ๊ฐ๋ฅ. ๋จ, ๋ค์ ๋ฌธ์ฅ์ ์ํ์ํฌ ๊ฒ. flush privileges; โข six tables in the mysl database: โข โข โข โข โข โข user db host tables_priv columns_priv func โ ์ด ์ค ์์ 5๊ฐ๊ฐ user privilege์ ๊ด๊ณ. (func ํ ์ด๋ธ์ userdefined function information์ ์ ์ฅ) โข ์์ 3๊ฐ tableโ user, db, and hostโ ์ database connection ์ ํ์ฉํ ์ง๋ฅผ ๊ฒฐ์ ํ๋๋ฐ ์ด์ฉ. 128 โข Understanding the user Table โ ์ฌ์ฉ์์ global privilege set์ ๋ํ ์ ๋ณด๋ก์ user table์ column์: โข Scope columns ; determine when a row is relevant. โ Host: Where the user is connecting from โ User: The username โ Password: The user's password, as encoded by the PASSWORD() function โข Privilege columns ; ๊ฐ๊ฐ ๋ค์์ global privileges์ ํด๋น. Y (๏ user has the global privilege) or N (๏ the user does not have global privilege)์ ๊ฐ์ ๊ฐ์ง. โ โ โ โ โ โ โ โ โ โ โ Select_priv Update_priv Index_priv Create_priv Grant_priv Reload_priv Process_priv Show_db_priv Create_tmp_table_priv Execute_priv Repl_client_priv Insert_priv Delete_priv Alter_priv Drop_priv References_priv Shutdown_priv File_priv Super_priv Lock_tables_priv Repl_slave_priv โข Secure connection columns ; grant๋ฌธ์์์ REQUIRE ์ ํ์. โ ssl_type โ x509_issuer ssl_cypher x509_subject โข Resource limitation columns ; ์ฌ์ฉ์ resource limitation. โ max_questions โ max_connections max_updates 129 โข Understanding the db Table โ stores a user's privileges for particular databases. โข Scope columns ; determine when a row of privileges is relevant. If you have different rules for different hosts, leave the host field blank and then create a corresponding set of rows in the host table to give more information. โ Host โ User Db โข Privilege columns ; specify whether the combination of Host, Db, and User have each of the listed privileges. ์ญ์ Y or N ๊ฐ์ ๊ฐ์ง. โ โ โ โ โ โ Select_priv Insert_priv Update_priv Delete_priv Index_priv Alter_priv Create_priv Drop_priv Grant_priv Create_tmp_table_priv Lock_tables_priv โข Understanding the host Table โ MySQL consults the host table when it finds a blank host entry in the db table. (๋จ, GRANT ๋ฌธ์ผ๋ก๋ ํจ๊ณผ๊ฐ ์๊ณ ๋์ manually set upํ ๊ฒ) โข Scope columns ; determine when a row of privileges is relevant. Each row here gives information for a single database accessed from a single host. โ Host Db โข Privilege columns ; specify whether the combination of Host and Db have each of the listed privileges. ; contain values Y or N. ๋จ, ํด๋น columns: โ โ โ โ โ โ Select_priv Update_priv Index_priv Create_priv Grant_priv Lock_tables_priv Insert_priv Delete_priv Alter_priv Drop_priv Create_tmp_table_priv 130 โข Understanding the tables_priv Table โ ๊ฐ๋ณ table์ ๋ํ user privilege๋ฅผ ํํ. โข Scope columns ; (์์ ์ค๋ช ์ฐธ์กฐ) + Table_name privilege (; lists the specific table that a grant applies to) โ Host โ User Db Table_name โข Grant columns ; ์ด privilege ๋ฅผ ๋๊ฐ, ์ธ์ grantํ๋์ง์ ๋ํ ์ ๋ณด. โ Grantor Timestamp โข Table_priv column ; determines what privileges the Host/Db/User has on the table listed in Table_name. โ ๊ฐ: Select, Insert, Update, Delete, Create, Drop, Grant, References, Index, Alter. โข Column_priv column ; table ๋ด ๋ชจ๋ column์ ๋ํ ์ฌ์ฉ์์ privilege๋ฅผ ์๋ ค ์ค. โ ์๋ก ๊ฐ: Select, Insert, Update, and References. 131 โข Understanding the columns_priv Table โ ๊ฐ๋ณ column์ ๋ํ user privilege๋ฅผ ํํ. ๋ค์ column ์๋ก: โข Scope columns ; determine when a row in this table is relevant. โ โ โ โ โ Host Db User Table_name Column_name โ โ โ โ Select Insert Update References. โข Column_priv column ; determines which privileges have been granted to the combination outlined by the scope column. โข Timestamp column ; tells when this privilege was granted. 132 12. Configuring MySQL โข Setting MySQL configuration options โข Multi-install configuration options โข Configuring for internationalization 133 Setting MySQL Configuration Options โข MySQL programs have configuration options. โ (๏ command line or) options file (ํ๋์ file์ ํตํด ์ฌ๋ฌ MySQL ํ๋ก ๊ทธ๋จ์ default option ์ง์ ) Specifically; โข mysql, mysqladmin, mysqld, mysqld_safe, mysql.server, mysqldump, mysqlimport, mysqlshow, mysqlcheck, myisamchk, and myisampack. โ ์ฅ์ : โข ํ์ค options๋ฅผ ์ด์๏ ์ฌ๋ฌ ์๋ฒ ์ด์ ์์ ํธ๋ฆฌ. (ํนํ replication ์ด์ฉ ์) โข Under Unix, MySQL also supports the use of: โ Per-server » = An options files for the each whole server (๋จ, ํ๋์ ํ๋์จ์ด์์ ์ฌ๋ฌ ๊ฐ์ MySQL server ์ด์๊ฐ๋ฅ) » a global options file (=ํ๋์ ๊ธฐ๊ณ ์์ ๊ฐ๊ฐ์ MySQL server์ ๋ํ options file) ; /etc/my.cnf์ ์์น » Per-server files are in in the data directory for each server. โ Per each individual users. » ์์น: ๊ฐ ์ฌ์ฉ์์ home directory. » per-user file์ prefixed with a dot (์: .my.cnf instead of my.cnf) โข Windows์์๋ you have a choice of: โ Windows ๋๋ ํ ๋ฆฌ์ my.ini or โ ์๋ฒ๊ฐ ์ค์น๋ ๋๋ผ์ด๋ธ์ root ๋๋ ํ ๋ฆฌ์ ๋๊ณ (์: C:\) my.cnf โ = a global options file๏ ์ฆ ์๋ฒ์์ ๋ชจ๋ ์ฌ์ฉ์์ ์ ์ฉ. 134 Listing 12.1 Sample my.cnf File [mysqld] # turn on binary logging and slow query logging log-bin log-slow-queries # InnoDB config # This is the basic config as suggested in the manual # Datafile(s) must be able to hold your data and indexes. # Make sure you have enough free disk space. innodb_data_file_path = ibdata1:10M:autoextend # # Set buffer pool size to 50 - 80 % of your computer's memory set-variable = innodb_buffer_pool_size=70M set-variable = innodb_additional_mem_pool_size=10M # # Set the log file size to about 25 % of the buffer pool size set-variable = innodb_log_file_size=20M set-variable = innodb_log_buffer_size=8M # # Set ..flush_log_at_trx_commit to 0 if you can afford losing # some last transactions innodb_flush_log_at_trx_commit=1 ์คํ๊ธฐ: [mysqld] ์ ์ฉ์ํค๊ณ ์ ํ๋ ํ๋ก๊ทธ๋จ ์ง์ . ๋ํ [client]๋ฅผ ํตํด ๋ชจ๋ client program์ ์ ์ฉ์ํค๋๋ก ํ ์๋ ์๋ค. <3 forms of syntax for setting individual options: > (I) Specifying the option you want switched on; ์: log-bin == mysqld --log-bin. (ii) Specifying the option you want with a value; ์: innodb_flush_log_at_trx_commit=1 (iii) Specifying the option you want with a value using the set-variable syntax; ์: set-variable = innodb_log_buffer_size=8M /* (iii)syntax๋ deprecated, but ์์๋ ๊ฒ. */์์ ํ์ผ (my.cnf)์ ๋งค๋ด์ผ์์ InnoDB configuration์์ */ Certain options work for all these programs: · --no-defaults ; no options files are to be read. · --print-defaults ; tell you what the values of all the options are being set to for this program. · --defaults-file=/path/to/file ; tell the program to use the specified file instead of any other options files it has. configuration ๋ณ๊ฒฝ์ testํ ๋ ํธ๋ฆฌ. · --defaults-extra-file=/path/to/file will read the specified file after reading the global options file but before reading any individual user options files. ๋ค๋ฅธ ๊ณณ์์๋ ๋๋ถ๋ถ ์ธ๊ธ๋จ. ๋จ, mysqld์ ๋ํด์๋ ์ดํ ์ค๋ช . 135 โข Setting Options for mysqld โข mysqld --help โ ์ฃผ์ options: โข ansi: โ ANSI ํธํ mode๋ก ์ํ. ๏ MySQL์์ ANSI-99 SQL ์ฌ์ฉ ๊ฐ๋ฅ. โข basedir: โ ๋๋ฆ๋๋ก์ ์ค์น base directory ์ค์ . โข datadir: โ basedir,์ ๊ฐ์ ํจ๊ณผ๋ฅผ ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ์ ๋ํด ์ ์ฉ โข log-bin: โ Turn on binary logging. (log์ ์์น/file๋ช ์ง์ ๊ฐ๋ฅ) โข log-error: โ Turn on error logging. Again, you can specify the location of the log. โข log-slow-queries: โ Turn on slow query logging. โข port: โ Specify the port that the server should listen on. Default๋ 3306. โข user: โ Specify the user that the MySQL server should run as. 136 Setting InnoDB Configuration Options โข Option์ง์ ์์ด InnoDB๋ฅผ ์ฌ์ฉํ ์ ์์ง๋ง option์ง์ ์ ์ฑ๋ฅ๊ฐ์ โ innodb_data_file_path = ibdata1:10M:autoextend โข InnoDB data๋ฅผ ๋ณด๊ดํ ์ฅ์ ์ง์ . MyISAM table (; table๋ณ๋ก ๋ณ๋ file)๊ณผ ๋ฌ๋ฆฌ, InnoDB tables are stored in a shared tablespace, which may consist of one or more files. โข (์ด ์์์๋) ๋ชจ๋ InnoDB data๋ฅผ ibdata1๋ผ๋ ํ๋์ ํ์ผ์ ๋ณด๊ด, initial file size=10MB, and to automatically make it bigger (8MB at a time) if the tablespace becomes full. โข (์ผ๋ฐํ) filename:filesize[;filename:filesize;...][:autoextend[:max:size]] โข The autoextend option allows the tablespace to grow. max option ; max size ์ง์ . โ innodb_buffer_pool_size=70M โข buffer size์ง์ (table data์ index๋ฅผ cache). Cache์ ๋ง์ฐฌ๊ฐ์ง๋ก ํด ์๋ก disk I/O๋ ์ค์ด๋ ๋ค. โข ์ง์ ๋๋ buffer pool์ ํฌ๊ธฐ๋ ์๋ฒ ์์ ๋ค๋ฅธ application ์ ๋ฌด, ๋ฉ๋ชจ๋ฆฌ ํฌ๊ธฐ ๋ฑ์ ๋ฐ๋ผ ๋ฌ๋ผ์ง. โ innodb_additional_mem_pool_size=10M โข sets aside memory to store internal MySQL data structures. If MySQL is running out of room here, it will begin writing warnings to the error log. โ innodb_log_file_size=20M โข sets the size of each log file. InnoDB rotates between n log filesโwhere n is the value set in the innodb_log_files_in_group option, which defaults to 2, the recommended value. โ innodb_log_buffer_size=8M โข ; sets the size of the buffer in which logs are stored before they are written to disk. โ innodb_flush_log_at_trx_commit=1 โข โข โข โข 1 ๋ก ์ง์ = transaction์ด commit๋ ๋๋ง๋ค log will be flushed to disk. (๊ฐ์ฅ ์ผ๋ฐ์ ํํ) 0์ผ๋ก ์ง์ ์; the log will be written to and flushed to disk only roughly once per second. 2๋ก ์ง์ ์; the log will be written to with each commit, but flushed only once per second. Values of 0 or 2 will improve performance, but are obviously a fairly risky proposition. 137 Multi-Install Configuration Options โข โข โข โข ํ๋์ ํ๋์จ์ด์์ ์ฌ๋ฌ ๊ฐ์ MySQL ์๋ฒ ์ํ (์: ISP users, ๊ต์ก) โ port: Each server must listen on a different port. โ socket: Under Unix, each server must use a different socket file. Under Windows, the socket option sets the name of the named pipe used by the server. In both cases, this value for socket must be different for each server. โ shared-memory-base-name (Windows only): ๊ฐ ์๋ฒ๋ ์๋ก ๋ค๋ฅธ shared memory ์ฌ์ฉ. โ pid-file (Unix only): ๊ฐ ์๋ฒ๋ process id (pid)๋ฅผ ๊ธฐ๋กํ ์๋ก ๋ค๋ฅธ ํ์ผ์ ํ์๋ก ํจ. โ Logging options: If you set any of the log file options, such as log-bin, you will need to set up different log file locations for each server. (๊ฐํธ๋ฒ) ์๋ฒ๋ง๋ค basedir option์ ๋ค๋ฅด๊ฒ ์ค์ ๏ force the data directories and log files to be different. (๊ถ๊ณ ) ์๋ฒ๋ง๋ค ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ๋ฅผ ๋ณ๋๋ก ์ค์ . --defaults-file option ์ ์ ์ฉ์ฑ = starting each server instance with a different set of defaults (or for installing each server as a Windows service with a separate set of defaults). (์ฐธ์กฐ) ์ฌ๋ฌ ๊ฐ์ (multiple) ์๋ฒ๋ฅผ ์ํํ๋ฉด ํด๋ผ์ด์ธํธ ํ๋ก๊ทธ๋จ, ๊ธฐํ (์: mysqladmin ๋ฑ)์๊ฒ ์ด๋ ์๋ฒ์ ์ฐ๊ฒฐํ ์ง๋ฅผ ์ง์ ํด์ผ ํ๋ค. โ --port command switch โ ์ด ๊ฒฝ์ฐ, ์ฌ์ฉ์ ๋ณ my.conf ๋ฅผ ํตํด ์ง์ ํ๋ฉด ํธ๋ฆฌ (๏ ์ฌ์ฉ์๋ณ๋ก ์์ ์ ์๋ฒ์ ์๋ ์ฐ๊ฒฐ) 138 Configuring for Internationalization โข ๋ค์ 2๊ฐ์ options to mysqld ์ ํตํด default character set๊ณผ collation ์ค์ . โ character set = the set of symbols used by default on the server. โ collation = the set of rules for performing comparisons, (sort orderโin the character set) โข --default-character-set option. Each character set has an associated default collation, โข --default-collation option. If the combination of default character set and default collation is not valid, mysqld will give you an error message. โข Default: โ default character set = latin1, โ default collation = latin1_swedish_ci. โข This character set can also be described as ISO-8859-1 West European, which is the one used in this book. The collation represents the sort order for latin1 used by the Swedes and Finns. โข There are also collations for latin1 that represent the ways that Germans, Danes, and Norwegians sort strings. 139 13. Administering Your Database โข Mysqladmin script ๋ฅผ ์ค์ฌ์ผ๋ก ์ดํด๋ด. ๋ํ โข mysqlshow scripts โข mysqlcheck scripts โข ๋ช ๋ น์ด: โ KILL, RESET, CHECK, REPAIR, and โ ANALYZE TABLE 140 Starting Up and Shutting Down the MySQL Server โข Under Linux โ start the server with โข /etc/init.d/mysqld start โข ๋จ, path์ง์ ์ ์. โ You can also start the server by running โข safe_mysqld โ To shut down your MySQL server โข /etc/init.d/mysqld stop or โข mysqladmin -u root -p shutdown โข root ๋ฐ privilege๋ถ์ฌ์ ์กฐ์ฌ. โ Figure 13.1. Services window in Windows Admin Tools (์๋ต) โ mysqladmin script for Linux๋ฅผ ์ด์ฉํด์ shutdown๋ ๊ฐ๋ฅ 141 Server ๋ฐ Database์ ๋ํ ์ ๋ณด์ ํ๋ โข Retrieving Database Information โข โข โข โข โข โข mysqlshow /* DB ์ ๋ณด์ ๊ณต. ๋จ, Parameter๊ฐ ์์ผ๋ฉด access๊ฐ๋ฅํ ๋ชจ๋ DB*/ = show databases; /*mysql monitor ๋๋ ๋ค๋ฅธ UI์์ ์ํ*/ mysqlshow -u username -p password ๋ ๊ฐ๋ฅ mysqlshow ?help /* ๏ a full list of these options.*/ mysqlshow -u username -p database /*ํน์ DB์ ๋ํ ์ ๋ณด (list of table)*/ mysqlshow -u username --status employee โ /* ๏ information about the storage engine used in each table, how much data is in each table, the current value of any auto-increment column in a table, and the character set used in each table. */ โ MySQL client๋ด์์ SHOW ๋ช ๋ น์ด ๏ database ๋ฐ ์๋ฒ ์ํ ์ ๋ณด. โข โข โข โข show show show show databases; and tables; /* ๏ databases and table์ ๋ํ ์ ๋ณด. ๋จ, options ์ด ๋ง์ */ columns from tablename; /* ๏ DESC statement.์์์ ๊ฐ์ ์ ๋ณด */ table status /* mysqlshow โstatus์ ๊ฐ์ ์ ๋ณด */ 142 โข Viewing Server Status and Variables โข SHOW STATUS /* inside MySQL, or */ โข mysqladmin -u username -p -extended-status /* command line์์*/ โข ๏จ ์๋ฒ ์คํ ์ดํ์ ํต๊ณ/์ ๋ณด. ์: โ com_select ; tells you how many select statements have been executed โ threads_connected: = current number of connections to the server. โ slow_queries: = number of queries this server has run that have taken more time than the value of the server variable long_query_time. These queries are logged in the Slow Query Log. โ uptime: This is how long this server instance has been running in seconds. โ To see the values of server variables, you can use โข show variables; /*from inside MySQL or */ โข mysqladmin -u username -p variables /*from the command line */ โข Viewing Process Information โข show processlist; โข mysqladmin -u username -p showprocesslist 143 โข Viewing Grant and Privilege Information show grants for username@host; ์: mysql> show grants for root@localhost; ๏จ +-------------------------------------------------------------------------------------------+ | Grants for root@localhost | +-------------------------------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | +-------------------------------------------------------------------------------------------+ 1 row in set (0.40 sec) โ To remind yourself what the various privileges are: โข show privileges; โข Viewing Reference Information About Tables โข show table types; โข show create table tablename; /* ์: */ show create table department; ๏จ CREATE TABLE 'department' ( 'departmentID' int(11) NOT NULL auto_increment, 'name' varchar(30) default NULL, PRIMARY KEY ('departmentID') ) TYPE=InnoDB CHARSET=latin1 โข (์ฐธ๊ณ : column names are quoted to be safe, and the default character setโwhich we didn't specifyโas specified here.) 144 โข Setting Variables โข set variable=value; ์: โข set sql_safe_updates=1; /*๏ turn on safe updates (=-i-am-a-dummy). โข Killing Threads โ โฆ โข kill process_id; โข Clearing Caches โ ์: update user privilege by manually altering grant tables ๏ ์ด๋ค ๋ณ๊ฒฝ์ฌํญ์ด roll through the system ์ฌ๋ถ๋ฅผ ํ์ธํ๋ ๊ฒฝ์ฐ: โข flush privileges; โข flush query cache; โข /* ๏ defragment the query cache๏ performance๊ฐ์ .*/ โ ๋๋ โข reset query cache; โข /*๏ query cache๋ฅผ defragmentํ๋ ๋์ , ์ค์ ๋ก clear it altogether.*/ 145 Understanding the Log Files โข Logging ํ์ ์์๋ ์ด๋ฅผ switch on์ํฌ ๊ฒ. (set ๋ช ๋ น์ด) โ Error log: โข ๋ฐ์๋ ๋ชจ๋ error๋ฅผ ์ถ์ (track). -- logged by default and appear in your data directory. โข (ํ์ผ๋ช : hostname.err (Linux) and mysql.err (Windows).) ์์น๋ฅผ ๋ณ๋๋ก ์ง์ ๊ฐ๋ฅ. option log-error=filename (in my.ini or my.cnf file.) โ Query log: โข ์ํ๋๋ ๋ชจ๋ query๋ฅผ log. You can turn on this log and specify the location with the option log=filename. โ Binary log: โข ๋ฐ์ดํฐ๋ฅผ ๋ณ๊ฒฝ์ํค๋ ๋ชจ๋ query๋ฅผ log. (๊ธฐ์กด update log๋ฅผ ๋์ฒด.) version 5.0 ์ดํ ์์ด์ง ๊ฒ. โturn on/ ์์น ์ง์ by the option log-bin=filename. โ Slow query log: โข long_query_time๋ณ์์ ์ ์ฅ๋ ๊ฐ๋ณด๋ค ์ค๋ ๊ฑธ๋ฆฌ๋ ๋ชจ๋ query๋ฅผ log. -- turn on/์์น ์ง ์ by the option log-slow-queries=filename โข ์ด๋ค์ (binary log์ ์ ์ธํ๊ณ ) ๋ชจ๋ text files. ๏ mysqlbinlog logfile ๋ช ๋ น ์ด๋ก ๋ณผ์ ์๋ค. ๋ํ ํฌ๊ธฐ๊ฐ ๊ณ์ ๋์ด๋๋ฏ๋ก regularly rotate your log files! โ Linux์ ๊ฒฝ์ฐ โข mysql-log-rotate script file์ด์ฉ โ LX ์ด์ธ์ ๊ฒฝ์ฐ โข move the old log files to a safe location manually and then tell MySQL to start using a new log file with the command 146 โข mysqladmin flush-logs mysqladmin Option Summary โ โ โ โ โ โ โ โ โ mysqladmin mysqladmin mysqladmin mysqladmin mysqladmin mysqladmin mysqladmin mysqladmin mysqladmin create databasename drop databasename ping version status extended-status processlist kill id1,id2,id3... variables 147 14. Backup ๋ฐ Disaster Recovery 148 Backing Up and Restoring Your Database โข ์ผ๋ฐ๋ก โ 4 ways you can make a backup in MySQL: โข mysqldump script ; creates a dump file, that is, a file containing the SQL statements necessary to re-create the database. โข mysqlhotcopy script ; creates a data file. This copies the data files for a particular database directly. โข ๋ฐ์ดํฐ ํ์ผ์ ์ง์ ๋ฐฑ์ โ mysqlhotcopy ๊ฐ ํ๋ ์ผ์ ์์์ ์ผ๋ก ํ๋ ๊ฒ. ๋จ, ์ด๋ copy์ ์ ํด๋น database๋ฅผ shut down ๋๋ ๋ชจ๋ table์ flush and lock (internal consistency๋ฅผ ์ํด์). โ Both mysqldump and mysqlhotcopy will flush and lock for you, so they are easier, safer options. โข BACKUP TABLE and RESTORE TABLE ๋ช ๋ น์ด; โ ์ฐธ๊ณ : โข ๋ชจ๋ backup์๋ ์์ ๋์ ์ฌ์ฉ์ access ์ ํ ๏ To take a consistent snapshot of a database, tables need to be flushed and held constant while the backup is performed. ์ฆ, ์๋ฒ๋ฅผ ์ ์ง์ํค๊ฑฐ ๋ ๋๋ table์ lock. โข ํ๋์ ํด๊ฒฐ์ฑ = replication. You can take down one slave and back it up while users continue blissfully about their business. 149 โข Backing Up and Restoring with mysqldump โ MySQL server๋ฅผ ์ ์ํ๊ณ SQL dump file ์์ฑ ( ๏ dump file์๋ DB re-create์ํ SQL ๋ฌธ์ฅ์ด ์๋ก๋์ด ์์) ์: โข mysqldump --opt -u username -p password employee > backup.sql โ ์ฌ๊ธฐ์: --opt option; encapsulates a few other options โ Using this script on the simple employee database ๏จ Listing 14.1. Listing 14.1 Sample Output from mysqldump -- MySQL dump 10.2 --- Host: localhost Database: employee ----------------------------------------------------------Server version 4.1.0-alpha-max-debug --- Table structure for table 'assignmentโ -DROP TABLE IF EXISTS assignment; CREATE TABLE assignment ( clientID int(11) NOT NULL default '0', employeeID int(11) NOT NULL default '0', workdate date NOT NULL default '0000-00-00', hours float default NULL, PRIMARY KEY (clientID,employeeID,workdate) ) TYPE=InnoDB CHARSET=latin1; 150 --- Dumping data for table 'assignmentโ -/*!40000 ALTER TABLE assignment DISABLE KEYS */; LOCK TABLES assignment WRITE; INSERT INTO assignment VALUES (1,7513,'0000-00-00',5),(1,7513,'200301-20',8.5); UNLOCK TABLES; /*!40000 ALTER TABLE assignment ENABLE KEYS */; --- Table structure for table 'clientโ -- DROP TABLE IF EXISTS client; CREATE TABLE client ( clientID int(11) NOT NULL auto_increment, name varchar(40) default NULL, address varchar(100) default NULL, contactPerson varchar(80) default NULL, contactNumber varchar(12) default NULL, PRIMARY KEY (clientID) ) TYPE=InnoDB CHARSET=latin1; --- Dumping data for table 'clientโ -- 151 /*!40000 ALTER TABLE client DISABLE KEYS */; LOCK TABLES client WRITE; INSERT INTO clientVALUES (1,'Telco Inc','1 Collins St Melbourne','Fred Smith','95551234'), (2,'The Bank','100 Bourke St Melbourne','Jan Tristan','95559876'); UNLOCK TABLES; /*!40000 ALTER TABLE client ENABLE KEYS */; --- Table structure for table 'departmentโ -DROP TABLE IF EXISTS department; CREATE TABLE department ( departmentID int(11) NOT NULL auto_increment, name varchar(30) default NULL, PRIMARY KEY (departmentID) ) TYPE=InnoDB CHARSET=latin1; --- Dumping data for table 'departmentโ -/*!40000 ALTER TABLE department DISABLE KEYS */; LOCK TABLES department WRITE; INSERT INTO department VALUES (42,'Finance'), (128,'Research and Development'), (129,'Human Resources'), (130,'Marketing'), (131,'Property Services'); UNLOCK TABLES; 152 /*!40000 ALTER TABLE department ENABLE KEYS */; --- Table structure for table 'employeeโ -DROP TABLE IF EXISTS employee; CREATE TABLE employee ( employeeID int(11) NOT NULL auto_increment, name varchar(80) default NULL, job varchar(30) default NULL, departmentID int(11) NOT NULL default '0', PRIMARY KEY (employeeID) ) TYPE=InnoDB CHARSET=latin1; --- Dumping data for table 'employeeโ -/*!40000 ALTER TABLE employee DISABLE KEYS */; LOCK TABLES employee WRITE; INSERT INTO employee VALUES (6651,'Ajay Patel','Programmer',128), (7513,'Nora Edwards','Programmer',128), (9006,'Candy Burnett','Systems Administrator',128), (9842,'Ben Smith','DBA',42), (9843,'Fred Smith','DBA',131); UNLOCK TABLES; 153 /*!40000 ALTER TABLE employee ENABLE KEYS */; --- Table structure for table 'employeeSkillsโ -DROP TABLE IF EXISTS employeeSkills; CREATE TABLE employeeSkills ( employeeID int(11) NOT NULL default '0', skill varchar(15) NOT NULL default '', PRIMARY KEY (employeeID,skill) ) TYPE=InnoDB CHARSET=latin1; --- Dumping data for table 'employeeSkillsโ -/*!40000 ALTER TABLE employeeSkills DISABLE KEYS */; LOCK TABLES employeeSkills WRITE; INSERT INTO employeeSkills VALUES (6651,'Java'), (6651,'VB'), (7513,'C'), (7513,'Java'), (7513,'Perl'), (9006,'Linux'), (9006,'NT'), (9842,'DB2'); UNLOCK TABLES; /*!40000 ALTER TABLE employeeSkills ENABLE KEYS */; 154 โข We could reload or re-create the employee database elsewhere by: 1. ์ ์ ํ ์ด๋ฆ์ DB๋ฅผ ์์ฑํ ํ 2. Loading this file using: mysql -u username -p < backup.sql โข mysqldump script์ options; โข --quick: tells MySQL to dump the data directly to the file, rather than buffering it in memory first (default). This will speed things up. โข --add-drop-table: Tells MySQL to add a DROP TABLE statement before each CREATE TABLE in the dump. โข --add-locks: Adds the LOCK TABLES and UNLOCK TABLES statements โข --extended-insert: use the multiline insert syntax to insert multiple rows with a single INSERT. ์์ ์์์: INSERT INTO employeeSkills VALUES (6651,'Java'), (6651,'VB'), (7513,'C'), โข /* If we have to use our backup to re-create the database, this will be faster to execute than a series of single INSERT statements. */ โข --lock-tables: lock all the tables before starting to dump. โ (์ฃผ์) --opt (meaning optimized) optimizes the length of time it takes to reload the dump file, rather than the length of time it takes to create the dump file ๏ Creating the dump file can be slow. 155 โข Here are a couple of other useful options: โ โ โ โ --databases: list more than one database for dumping. --all-databases: dump all the databases it has in storage. --allow-keywords: MySQL keyword๋ฅผ column์ด๋ฆ์ผ๋ก ์ฌ์ฉ ์ ์ง์ -d or --no-data: Dumps only the database structure, not the contents. ์ฌ๋ฌ ์๋ฒ์ DBํ ์คํธ ๋๋ deploy์ ์ ์ฉ. โข ์ฅ๋จ์ โ ์ฅ์ : simple to use and it takes care of table locking issues for you. โ ๋จ์ : โข this script locks tables: Table ํฌ๊ธฐ์ ๋ฐ๋ผ ์ ์ด, ์ ๋ถ.. ๋ฐ๋ผ์ nonpeaktime์ ์ํ. โข Because mysqldump works through the MySQL server, it will be slower to run than mysqlhotcopy. โข mysqlhotcopy ๋ MySQL server ์์ฒด๋ ๋ณ๋ก ์ด์ฉ์น ์๊ณ ์ง์ ํ์ผ ์์คํ ์ด์ฉ. 156 โข Backing Up and Restoring with mysqlhotcopy โ mysqlhotcopy โข (ํน์ง) copies the actual database data files, rather than retrieving data through a connection to the server. โข ์ฆ, DB table์ flush ๋ฐ lockํ๊ธฐ ์ํด DB์๋ฒ์ connection์ ์ค์ ํ์ง๋ง ์ฃผ๋ก ํ์ผ์์คํ ์ค์ฌ์ด๋ฏ๋ก mysqldump๋ณด๋ค ๋ค์ ๋น ๋ฅด๋ค. โ ์ฌ์ฉ: โข mysqlhotcopy -u username -p database_name backup_location โข Perl script์ด๋ฏ๋ก (Ux/Lx์์๋ ์๊ด์์ผ๋) Windows์์๋ download Perl for Windows www.activestate.com/Products/ActivePerl โ The files produced by mysqlhotcopy are replicas of the database data files. To use these backups, you should stop the MySQL server and replace the data files in the MySQL data directory with the backed-up files. 157 โข Backing Up and Restoring Manually โ = flush and lock the tables and copy the data files to a backup location while the tables are still locked. 1. LOCK TABLES ๋ช ๋ น์ด lock tables employee read, department read, client read, assignment read, employeeSkills read; โข /* LOCK TABLES ๋ฌธ์ฅ์ parameters = a list of table names and the type of lock we would like to acquire, READ or WRITE. */ โข ์ผ๋ฐ์ ์ผ๋ก๋ backup์ ์ํด์๋ read lock์ด๋ฉด ์ถฉ๋ถ. ์ฆ, other threads (connections) can continue to read from the tables but will be unable to write to them while performing a backup. โข Backup์ด ์ค๋ ๊ฑธ๋ฆฌ๋ฏ๋ก Locking์ ์ค์. 2. FLUSH TABLES ๋ช ๋ น์ด: โข flush tables; โข ์ ์ฒด DB ๋ฐฑ์ ์์๋ ๋ค์ ๋ช ๋ น์ผ๋ก ํ๋ฒ์ ์ฒ๋ฆฌ ๊ฐ๋ฅ. flush tables with read lock; 3. (์ค์) leave your session (where you locked and flushed the tables) open. This makes sure that the locks are maintained. When you close that session, the tables will be unlocked. 4. File copy ํ table์ unlockํ ๊ฒ. 158 โข unlock tables; โข /* mysqlhotcopy script์ ๋ง์ฐฌ๊ฐ์ง, and you can restore in the same way. */ โข BACKUP TABLE and RESTORE TABLE โ MyISAM table type์๋ง ์ ์ฉ๊ฐ๋ฅ. ์: โข backup table t1 to 'path/to/backup'; โ Windows์์๋ ๋๋ผ์ด๋ธ ์ง์ ํ ๊ฒ.์: โข backup table t1 to 'c:/path/to/backup'; โข /* The table will be read locked before it is backed up. */ โ ์ฌ๋ฌ table์ comma๋ก ์ฐ๊ฒฐ ๏ ๊ฐ table์ ์ฐจ๋ก๋ก locked & backed up. โข consistent set of table์ด ํ์ํ๋ฉด LOCK TABLES ๋ฌธ์ฅ์ ๋จผ์ ์ํ. โ To restore from the backup, โข restore table t1 from 'c:/tmp'; โข /* ๋ง์ฝ ๊ฐ์ ์ด๋ฆ์ table์ด ์๋ ๊ฒฝ์ฐ DROP TABLE ๋จผ์ ์ํ ํ RESTORE. */ โข Restoring from the Binary Log โ ๋๋ถ๋ถ; backup์ผ๋ก๋ถํฐ restoreํ์ ๋๋ ์ฒ์ backupํ ์ด๋๋ก ๋ฐ์ํ insert/update๋ฅผ ๋ฐ์ํ๋ ์์ ์ด ํ์. โ ์ด๋ค ๋ณ๊ฒฝ์ฌํญ์ binary log or update log์ ์ ์ฅ๋์ด ์๋ค. โข mysqlbinlog logfile > updates.sql โ (์ฃผ์) ์์ ๋ด์ญ์ ๋ฏธ๋ฆฌ ์ ๊ฒ! ์: โข update user set password='password'; โข ์ฆ, ์ด๋ฐ ์์ ์ด ์ฌ ์คํ๋์ง ์๋๋ก ์ฃผ์. 159 Testing Your Backup โ โฆ โ Testํ ๊ฒ โ ํนํ install ๋ฐ recovery์์ binary log๊ฐ ์ค์. โข It is not enabled by default, but it is needed to bring a restored database back up to date. 160 Checking and Repairing Tables โข Checking tables for corruption is part of routine job โข MySQL์์ table checkํ๋ 3๊ฐ์ง ๋ฐฉ๋ฒ: โ CHECK TABLE โ myisamchk (or isamchk) โ Mysqlcheck โข ๋ฌธ์ table์ repair; โ REPAIR TABLE or โ again myisamchk (or isamchk) or mysqlcheck. โข ์ด๋ค option์ ์ฌ์ฉํ ์ง๋ฅผ ์ ํ๋๋ฐ ๊ณ ๋ คํด์ผ ํ ์ฌํญ: CHECK /REPAIR ๋ช ๋ น์ด๋ MySQL๋ด์์, ๋ค๋ฅธ ๋ฐฉ๋ฒ๋ค์ ๋ช ๋ น์ด ์ค์์ ์ํ. CHECK /REPAIR ๋ช ๋ น์ด๋ MyISAM๊ณผ InnoDB table ๋ชจ๋์ ์ ์ฉ isamchk script๋ ISAM์, myisamchk์ mysqlcheck๋ MyISAM์ ์ ์ฉ. myisamchk /isamchk ์ด์ฉ ์๋ table์ ์ฌ์ฉํ๊ณ ์์ง ์์์ผ ํ๋ฏ๋ก locking ๋ฑ์ ์กฐ์น. ๏๏ ์์นซ data corruption. โ CHECK, REPAIR, and mysqlcheck are all safe to use when the server is up and tables are in use. โ (๊ณ์) โ โ โ โ 161 โข Checking and Repairing Tables with CHECK and REPAIR โ ์: check table department; /* MyISAM and InnoDB tables ๋ชจ๋ ๊ฐ๋ฅ. */ ๏จ +-----------------------------+---------+-------------+-------------+ | Table | Op | Msg_type | Msg_text | +-----------------------------+---------+-------------+-------------+ | employee.department | check | status | OK | +-----------------------------+---------+-------------+-------------+ 1 row in set (0.00 sec) โ ๋๋ โTable is already up to dateโ, ์ฆ, everythingโs fine. โ ๋ค๋ฅธ message =๋ฌธ์ ๋ฐ์ํ ๊ฒ์ด๋ฏ๋ก ๏ REPAIR TABLE : repair table t1; โ Repair๊ฐ ์ ์์ ์ผ๋ก ๋๋ฉด (or ์ ๋น์ด repair๊ฐ ๋ถํ์ํ์ผ๋ฉด) ๏จ +---------+--------+--------------+-------------+ | Table | Op | Msg_type | Msg_text | +---------+--------+--------------+-------------+ | test.t1 | repair | status | OK | +---------+---------+--------------+-------------+ 1 row in set (0.03 sec) โ If you get any message other than OK, the REPAIR hasn't worked and you will need to resort to the more powerful myisamchk. 162 โข Checking and Repairing Tables with myisamchk โ (์ฃผ์) myisamchk ์ฌ์ฉ ์ stop the server! โ ์ฉ๋ก: myisamchk table /* at the command prompt. */ โข /* The table should be the path to a .MYI file that represents a MyISAM table. This will report virtually all errors. If it doesn't seem to be finding your problem, you can try running it with the -m switch. The default behavior looks for corruption in the indexes; with this switch, the rows are scanned as well. */ โ myisamchk์ ์ด์ฉํ repair โข -q -r options for quick recovery, as shown here: myisamchk -q -r table โข /* ์๋๋ฉด back up the data file and try a full recovery: */ myisamchk -r table โข /* ์๋๋ฉด try --safe-recover option ; -r ๋ก ์ฒ๋ฆฌ ์๋ error๋ฅผ fix: */ myisamchk --safe-recover table โข /* myisamchk ์ parameter์์ด ์ ๋ ฅํ๋ฉด ๋ง์ option์ ๋ณผ ์ ์๋ค. */ 163 โข Checking and Repairing Tables with mysqlcheck โ mysqlcheck program ; checks MyISAM and InnoDB tables and repairs MyISAM tables safely while the server is up and running. โข mysqlcheck -u username -p employee โ ์๋ฌด ๋ฌธ์ ์์ ๋์๋ ๏จ โข โข โข โข โข employee.assignment employee.client employee.department employee.employee employee.employeeSkills OK OK OK OK OK โ --databases switch ; specifies a list of databases to check โ --all-databases option ; checks all the databases on the server. โ -r option ; repairs any corrupted MyISAM tables that it encounters. 164 15. Securing Your MySQL Installation 165 How the Privilege System Works in Practice โข two stages to the privilege system. โ 1 ๋จ๊ณ โข ์ฌ์ฉ์๊ฐ ์๋ฒ์ ์ฐ๊ฒฐํด๋ ๋๋์ง ํ์ธ โ์ ๋ ฅ๋ username/ password๊ณผ host ๋ฅผ ๋น๊ต -- user table ์ด์ฉ. ์ฆ, matching row๊ฐ ์์ด์ผ ๋จ โข user table์ด host column์์ wildcard๋ฅผ ์ง์ํ๋ฏ๋ก user/hostname combination์ด ์ฌ๋ฌ ๊ฐ์ row์ match๋ ์ ์๋ค. MySQL determines which row is relevant by matching the most specific hostname first. โ ์: if there are rows in the table for test from host localhost and user test from host % (meaning any host), then the localhost row will be selected. Note that these two rows can have different passwords. ๏ confusion. โ 2 ๋จ๊ณ โข ํน์ query or command ์ํ ์ grant table๋ก ํ์ธ ํ ์ํ. โ ์ํํ๋ ค๋ query๊ฐ global privilege๋ฅผ ํ์๋ก ํ๋ ๊ฒฝ์ฐโ์: LOAD DATA INFILE or trying to use SHOW PROCESSLISTโuser table์ check. โ For database-specific queries, the user table will be checked first. โ If the user has the privilege on all databases, this will be sufficient. โ If not, then the db and host tables are checked. โ If (์ฌ๊ธฐ์๋ ํ์ธ ์๋๋ฉด) then ๋ง์ง๋ง์ผ๋ก table- or column-level privileges ํ์ธ. 166 Securing Accounts โข Setting the Password for the Root Account โ MySQL์๋ฒ ์ค์น ์ ๋ฐ๋์ ์ฆ๊ฐ root password๋ฅผ ๋จผ์ ์ค์ ํ ๊ฒ. (default์ค์ x) โข Deleting Anonymous Accounts โ MySQL์ Windows์ ์ค์นํ ๋, ์๋์ ์ผ๋ก ํน์ account๋ฅผ ์์ฑ โ Linux์ ๊ฒฝ์ฐ์๋ mysql_install_db script์ํ ์ ๋ฐ์. โ Two of these accounts are anonymous; (No passwords set by default) โข host value of localhost and โข % (any other host, so effectively any remote connection). โ Delete these accounts!! delete from user where User=โ โ; delete from db where User=โ โ; โข /* follow this with FLUSH PRIVILEGES to flush the grant tables. */ โ (๋ค๋ฅธ ์ด์ ) ์ด๋ค account๊ฐ ํผ๋์ผ๊ธฐ when regular users try to log in. โข ์์ปจ๋ laura ๋ผ๋ username at any host (%)๋ฅผ ์์ฑ ๏ โข laura tries to connect from localhost ๏ MySQL server looks for matching entries in the user table. It has laura@% and (anonymous)@localhost. โข ์ด๋ MySQL์ the most specific hostname์ ์ฐ์ ์ ์ผ๋ก match์ํค๋ฏ๋ก matching row๋ (anonymous)@localhost๊ฐ ๋๋ค. Note that although laura has supplied a username, this doesn't matter! The anonymous accounts don't require a username. This anonymous account is likely to have a different password from laura's account (by default, the password is blank, meaning the user should not supply one). ์ฆ, when laura tries to log in with her username and password from localhost, she will get an Access Denied error for no obvious reason. 167 โข Dangerous Privileges โ MySQL has a very fine-grained privilege system์ ๊ฐ์ง๋ค. (Ch 11) ๋ฐ ๋ผ์ privilege grant์ ์ฃผ์. ํนํ FILE, PROCESS, and WITH GRANT OPTION์ ์กฐ์ฌํ ๊ฒ! โ FILE privilege ; allows users to LOAD DATA INFILE. This can be manipulated to load in files from the server (such as the password file /etc/passwd) or even database data files, effectively circumventing the privilege system. โ PROCESS privilege ; allows users to SHOW PROCESSLIST. (์ด๋ ์ ํ ์ค์ธ query ๋ฑ ์ฌ์ฉ์ ๊ด๋ จ ์ ๋ณด๊ฐ ์ ์ถ๋ ๊ฐ๋ฅ์ฑ) โ WITH GRANT OPTION privilege ; allows a user to share his privileges with others. ๋ฐ๋ผ์ ์ํ์ฑ์ ๋ช ํํ ์ธ์ํ ์ํ์์๋ง ์ฌ์ฉ. โข Passwords and Encryption โ MySQL user passwords are encrypted. Before version 4.1, you could use the encrypted password as stored to log in. This has now been fixed. โ (non-MySQL) username ๋ฐ password ์ ์ฅํ๋ ํ๋ก๊ทธ๋จ ๊ฐ๋ฐ ์ PASSWORD() ํจ์๋ณด๋ค๋ MD5() or ENCRYPT()๋ฅผ ์ด์ฉํ ๊ฒ.See Ch 8. 168 Securing Your Installation Files โ ์์์ ํญ๋ชฉ ์ด์ธ์๋ MySQL binaries, scripts, and data files์ ๋ํ access๋ฅผ ํต์ ํ ๊ฒ! โข Don't Run mysqld as Root โ โฆ โ (Web server ์์์ฒ๋ผ) ๋ณ๋ ๊ณ์ ์ ์์ฑ โข Access and Privileges Under Your Operating System โ ๋ฌด์๋ณด๋ค control file access in your operating system !! โข MySQL binaries, scripts, ํนํ data directory์ ๋ํ ์ฌ์ฉ์ access๋ฅผ ํต์ ! โข ํํ ์ค๋ฅ = ์๋ฒ๊ฐ ์๋ ์์คํ ์ ๊ณ์ ์ ๊ฐ์ง ์๊ฐ ์์นซ ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ์ ๋ค์ด์์ ๋ค๋ฅธ MySQL ์๋ฒ๋ก ๋ฐ์ดํฐ ๋ณต์ ํ๋ ๋ฌธ์ . โ (following safeguards) โข Only appropriate users can run mysqld. โข ์ ์ ํ ์ฌ์ฉ์๋ง์ด โ MySQL์ ์ฐ๊ด๋ program๊ณผ script์ accessํ ์ ์๋๋ก ํ ๊ฒ. (์: mysqladmin, mysqldump, mysqlhotcopy. โ program ๋ณ๋ก ๊ฒ์ฌํ ๊ฒ). โ MySQL data directory์ accessํ ์ ์๋๋ก ํ ๊ฒ. If the server is running as user mysql, this user will need access to the directory. Any other users are optional and are therefore generally best denied. 169 Filtering User Data โข Before passing on any user-entered data to MySQL, you should do some application-level error checking. โ ์: user name์์์ โ (apostrophe) 170 Other Tips โข Using SSL Connections โ โฆ โ OpenSSL library (available from www.openssl.org)๋ฅผ ์ค์นํ๊ณ start the server with the --with-vio and --with-ssl options, and do some setup at the command line. (MySQL manual ์ฐธ์กฐ) โ ์ค์น ํ restrict GRANT statements by requiring users to connect using SSL or to have an appropriate certificate. ์: โข grant all on employee.*to testuser identified by 'password'require ssl; โข /* This creates (or modifies) an account for testuser, giving the user the password password. This user will be able to connect only via SSL. You can demand that all your users connect this way or perhaps all users logging in from anywhere other than localhost. */ โข Securing Your Installation Physically โ โฆ ์ค์ โฆ 171 16. Replicating Your Database 172 Replication Principles โข ๋ค์ํ Replication ํํ ์ค MySQL์ directional master-slave relationship. โ Master controls what data is stored, while the slaves try to mirror that content. โ Master์ binary log stores details of every query executed on the server since logging was enabled. Slaves are sent queries from the master's binary log to apply to their own stored data. โ ์ผ๋ฐ์ ์ผ๋ก write operation์ ์ง์ master์ ์ํํ๊ณ read operation์ ๋ชจ๋ slave ๋ ๋ master-slave๊ฐ์ ๊ณต์ . ๏ ํต์ application logic. โ (์ ์) ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง ๊ธฐ์กด database์ replication ์ถ๊ฐ ์ ๏ the binary log may be incomplete. Binary logging๋ ์๋ (by default) ๊ตฌ๋๋๋ ๊ฒ์ด ์๋๋ฏ๋ก ์ ์์ ๋ณต์ ๋ฅผ ์ํด์๋ binary log ์์ํ ์์ ์ ๋ชจ๋ slave๊ฐ master์ ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ผ ํ๋ค. ๏ โ A thread on the slave connects to a thread on the master and requests new events. These are stored in a relay log on the slave. A separate thread on the slave reads events from the local relay log and executes the queries on the local mirror of the data. โ Master์ slave๊ฐ ์๋ก ๋ค๋ฅธ ์์ ์ ์์๋ ์ ์์ผ๋ฏ๋ก (์: query๋์ค ์์คํ ์ถ๊ฐ ๋๋ ๋คํธ์ํฌ fail ๋๋ bottleneck๋ฐ์), slaves need to be able to keep track of where they are in the log of updates to be performed. It is important that atomic transactions are honored and updates are performed in order. โ ๋๋ถ๋ถ consistent state๋ก ๋ณต์ ๋๊ธฐ๋ง ํ๋ฉด ๋ช ๋ถ (์ด)์ ์๊ฐ์ฐจ์ด๋ ํฌ๊ฒ ์ค์์น ์๋ค. โ (๋ด๋ถ์์ฉ) Updates are asynchronous and do not happen in real time. Queries sent to different servers can give different results for some time after an update is made. This can be seen as a negative, but the positive side is that if you have a slave running on a portable device or an unreliable network, it will happily operate for long periods between updating data from the master. โข A Note on Versions โ MySQL (3.23.15)๋ถํฐ ์ ์ฉ. ๊ฐ๊ธ์ ์ต์ version์ผ๋กโฆ Older version์ด ๋ถ๊ฐํผํ๋ฉด 173 โข www.mysql.com/doc/en/Replication_Implementation.html Setting Up and Configuring for Replication โข (์ผ๋ฐ๋ก ) โ Internet์ฌ์ฉ ์ ๋ณด์ ๋ฌธ์ โ 3306 default port๊ฐ firewall์ ํต๊ณผํ ์ ์๋์ง ํ์ธ. โข Create a Replication User โ Master์์์ replication์ ์ํ ๊ณ์ ๏น root โ If you are going to populate your slaves initially by using LOAD TABLE FROM MASTER or LOAD DATA FROM MASTER, your replication user needs a special set of permissions. โ ์: ์ฐ๊ฒฐ์ค์ ์ ์ํด์๋ ํ์ permission์ ๊ฐ์ง ์ฌ์ฉ์ ๊ณ์ ์ ์์ฑ grant replication slave, reload, super, select on logs.* to replication@" %" identified by 'password'; โข (Note: ์ฌ๊ธฐ์๋ logs database ์ด์ฉํ๋ฏ๋ก ์ด๋ฅผ ๋ณ๊ฒฝ์์ผ ์ค ๊ฒ.) โ ์ผ๋จ initial copy from master to slave๊ฐ ์์ ํ ์ํ๋๋ฉด replication ์ฌ์ฉ์๋ ๊ทธ๋ฆฌ ๋ง์ permission์ ํ์๋ก ํ์ง ์๋๋ค. If you are populating your slaves from a backup or reducing the user's permissions after the initial copying is complete, the user needs only the replication permission, so the following query will create a user named replication that can connect from any of the slave servers (and any other machines): โข grant replication slave on logs.* to replication@"%" 'password'; identified by 174 โข Check Master Configuration โ Master server์์๋ binary logging์ด enabled ๋์ด์ผ ํ๋ค. โฆ โ ํ์ธ: โข show variables; /* ๏ complete list */ โข show variables like "log_bin" ; /*, but for concise output */ โ If binary logging is off, add log-bin to options file as in Listing 1.1. โข โข โข โข Options file์ ์ด๋ฆ= my.ini or my.cnf (์ด์์ฒด์ ์ ๋ฐ๋ผ ๋ฌ๋ผ์ง) Edit your my.ini/my.cnf file to give your master server a unique id. ์: [mysqld] log-binserver-id=1 ์ฌ๊ธฐ์ server-id๋ MySQL ์๋ฒ๋ง๋ค ํ ๋น๋๋ unique identifier ๋ก์ ์์ ์ ์ (a positive integer)์ฌ์ผ ํ๋ค. โ options file ํธ์ง ํ์๋ ์๋ฒ๋ฅผ restartํด์ผ ํจ๋ ฅ ๋ฐ์. 175 โข โ โ Create a Master Snapshot Replication์ ์ํด์ ๋ค์์ 3๊ฐ์ง๊ฐ ํ์ 1. 2. 3. A complete, consistent snapshot of the current database Master ์๋ฒ์ binary log file ์ด๋ฆ The offset into the binary log where the server is currently ์ด๋ค์ ๋ค์ ์์ธ์ ์ํด ์ํฅ (i) MyISAM or InnoDB tables (ii) ํน์ ๊ธฐ ๊ฐ ๋ด์ ์๋ฒ ์ ์ง๋ฅผ ์ผ๋ง๋ ํ์ฉํ ๊ฒ์ธ๊ฐ์ ๋ฌธ์ . โข โข MyISAM table; you can grab a snapshot after you start each slave. ; ๋น ํจ์จ์ , ํนํ if you have a large amount of data and many slaves. For each slave, the LOAD DATA FROM MASTER query will obtain a lock on the master's data and hold it until a complete copy has been transmitted. You can lock the databases for a much shorter time by making the snapshot manually via the file system. This will also allow you to use one snapshot to start as many slaves as required, reducing time when the server is locked. InnoDB table; LOAD DATA FROM MASTER query option์ด ์๋ค. โ โ โ You can make a file-system snapshot or buy the hot backup tool. ์ด ๊ฒฝ์ฐ ์ฐ์ ๋ค์ ๋ช ๋ น์ ํตํด ๋ณด๊ด๋ ๋ฐ์ดํฐ๊ฐ consistent & up-to-date ํ์ง ํ์ธ. get the current binary log file and offset flush tables with read lock; /* This will also lock the table. */ show master status; +-------------------------+------------+------------------+------------------------+ | File | Position | Binlog_do_db | Binlog_ignore_db | +-------------------------+------------+-------------------+------------------------+ | server-bin.000007 | 211 | | | +-------------------------+-------------+------------------+------------------------+ โ ์ฒซ์งธ (binary log ํ์ผ์ด๋ฆ) ๋ฐ ๋์งธ column (offset into the binary log)๋ด์ฉ์ 176 ๊ธฐ๋ก. ์ด๋ค ๋ด์ฉ์ด empty์ด๋ฉด ํ์ผ์ด๋ฆ์ผ๋ก๋ empty string ๊ทธ๋ฆฌ๊ณ offset์ผ๋ก๋ 4๋ฅผ ์ด์ฉ. โ MyISAM table์ snapshot์ ๋ง๋ค๋ ค๋ฉด ๋จ์ง ๋ฐ์ดํฐ๋ฅผ ๋ณด๊ดํ ๋๋ ํ ๋ฆฌ๋ฅผ archiving program์ ์ด์ฉํ์ฌ ๋ณต์ฌํ๋ฉด ๋๋ค. โข Unix์์๋: tar -cvf /tmp/snapshot.tar /path/mysql/data/logs โข Windows์์๋:WinZip or ๊ธฐํ archiving tool์ ํตํด grab a copy of the directory C:\mysql\data\logs. โ copy๊ฐ ์๋ฃ๋ ํ re-enable write access to the database by typing: unlock tables; โ ์ด์์ ๋ ผ์๋ InnoDB table์ ๋ํ ๊ฒ. โข If you have purchased the (commercial) InnoDB hot backup tool, it is perfect for this task. (www.innodb.com/hotbackup.html) โข Without this tool, the safest approach is to flush and lock the database with the following queries. Use โข flush tables with read lock; โข /* ๊ทธ๋ฐ ํdisplay and record the binary log file and offset (as for MyISAM): */ show master status; โ Without unlocking the database, shut it down and make a copy of the directory that relates to that database inside your MySQL data directory. For InnoDB tables, you will also need to copy across the data files and logs. After snapshot is complete, you can restart and unlock database. 177 โข Configure Slaves โ ๊ฐ slave๋ ๊ณ ์ ํ server id๋ฅผ ํ์๋ก ํ๋ฏ๋ก optionsํ์ผ (my.cnf/my.ini)์ ๋ค ์ ๋ด์ฉ์ ์ฝ์ . โข server-id=2 โ The id = positive integer (๋จ, ์๋ก ๋ค๋ฅธ ์ซ์์ด๊ธฐ๋ง ํ๋ฉด ์ด๋ค ๊ฐ๋ ์๊ด์์) If you are going to have more than a handful of servers running, an escalating sequence is probably your best hope of keeping them unique. โ If you are working from a file-system snapshot, you need to copy the files into the appropriate places on the slave server. โ If you are working with more than one operating system, remember to consider filename capitalization. โ Editing your options file or copying across InnoDB files will require you to restart your slave server. 178 โข Start Slaves change master to master_host='server', master_user='replication', master_password='password', master_log_file='server-bin.000007', master_log_pos=211;start slave; โข /* ์ด ์์์ server = hostname of the master server. replication = replication์ ์ํด ์์ฑํ ์ฌ์ฉ์์ username password = ๊ทธ ์ฌ์ฉ์์ ์ํธ. ๊ทธ ์ธ์ binary log file name ๋ฐ offset โข START SLAVE query ; launches the slave's replication threads, causing it to try to connect to the master and collect updates. */ โ If you have copied a snapshot via the file system, you should be able to run some matching queries against the master and slave to check that the replication is working correctly. Make a small update to the master and check that it is mirrored on the slave. โ If the tables you are replicating are relatively small MyISAM tables, you can create and populate them via a query like load table logs.logJan2003 from master; /* copy a single table or */ load data from master; /* to copy all tables onto this slave. */ โ replication ๋์ ํ์๋ query๋ฅผ manually ์ ๋ ฅํด์ configure replicationํ๋ ๊ฒ์ practicalํ์ง ์๋ค. (, even if only occasionally.) ๊ฐ์ ์ ๋ณด๊ฐ The options file์์๋ slightly different syntax! ์: [mysqld] server-id = 2 master-host = server master-user = replication master-password = password replicate-do-db = logs ` 179 Advanced Topologies โข ๊ฐ์ฅ ์ผ๋ฐ์ ์ธ ์ฌ์ฉ์ฒ; load balancing (์ฃผ๋ก ๋ง์ read์ ์๋์ ์ผ ๋ก ์ ์ writes). ๋๋ถ๋ถ single master + a small number of slaves โข Slave ์๊ฐ ๋ง๊ฑฐ๋ ์ง์ญ์ ์ผ๋ก spread๋๋ฉด cascade. โ Figure 16.1. Replication with Cascading Masters โข ์ํ ๊ด๊ณ(circular relationship) ์ ๋ณต์กํด ์ง ์ ์๋ค. ์: ์์คํ 2 ๋๊ฐ ์๋ก master-slave/slave-master๋ก ์ฎ์ธ ๊ฒฝ์ฐ ํ๋ก๊ทธ๋๋ฐ ์ฃผ์. โ Because changes are applied asynchronously, you can end up with conflicting auto increment fields, clashing unique ids, and inconsistent data. In some applications, this arrangement may work well. For instance, a data logging application with few relationships between tables that requires high throughput and availability may be willing to sacrifice consistency. 180 Replication Future โข standard distribution ์ ํฌํจ๋์ด ์๊ณ ์๋นํ ์์ ๋์์ผ๋ ์ผ๋ถ ๋ฏธ์งํ ์ : โ the process for setting up a new slave with a snapshot is not very userfriendly. โ The treatment of MyISAM tables and InnoDB tables is not consistent. โ Options for setting up SSL connections between slaves and masters. โ MyISAM์๋ InnoDB์์์ ๊ฐ์ hot backup tool์ด ์์ ๊ฒ. โข ํฅํ ๊ณํ: โ multimasteringโํ๋์ slave๊ฐ ์ฌ๋ฌ master๋ฅผ mirrorํ๋ฉด์๋ resolve conflict. โ built-in failover and load-balancing features. โข ํ์ฌ๋ application์์ ํด๊ฒฐํ๋๊ฐ ๋๋ 3rd-party clustering tool ํ์. (EAC) โข Some replication-related settings in the options file that are currently unimplemented. โ Currently, if you want to make secure connections, you need to use another product, such as Stunnel. 181 17. MySQL ์๋ฒ Configuration์ ์ต์ ํ โข Do it empirically. โ ํ๋์ฉ ๋ฐ๊ฟ ๊ฐ๋ฉด์ ์ด์ ๊ณผ ๋น๊ต โ Benchmark ์์๋ log a period worth of queries (an hour, a day, or some average period) and then replay those queries with the new server configuration. 182 Compiling and Linking for Speed โข ์ง์ ์ปดํ์ผ ๏ ์ฑ๋ฅ ํฅ์: extra 10% to 30% โ If you have a Pentium-based machine and run Linux, you will be able to get a significant performance increase by compiling MySQL with the pgcc compiler, which optimizes for Pentium only. โ With AMD chips compiled with plain gcc. โข ํ์ํ character set(s)๋ง ์ ์ฉํ๊ณ Compile 183 Tuning Server Parameters โ ํ์ฌ์ ์ค์ ์ํ ํ์ : show variables; โ See the effects of your server configuration: show status; โ ํ์ฌ ์๋ฒ์ ์งํ ์ํฉ์ Monitor: Jeremy Zawodny's mytop Perl script. http://jeremy.zawodny.com/mysql/mytop โข = Unix top command์ ์ ์ฌ โข shows what processes are active, the process state, the time spent, etc.+ drill into a MySQL process and see the actual query being executed. โข Server parameters in my.cnf options files โ MySQLโs sample my.cnf files in the support-files directory. โข 4 suggested my.cnf files in this directory: my-huge.cnf, my-large.cnf, mymedium.cnf, and my-small.cnf. โข (์ดํ ๋ค์ ํ์ด์ง์ โฆ) โข 2๊ฐ์ ๊ฐ์ฅ ์ค์ํ parameters: key buffer์ table cache โข (์ด์ธ์๋) ๋ค์ํ chunks of memory allocated on a per-thread basis โ read buffer size, controlled by the read_buffer_size parameter, โ The sort buffer, controlled by the sort_buffer parameter, 184 โข 2๊ฐ์ ๊ฐ์ฅ ์ค์ํ parameters: key buffer์ table cache โข ์ด๋ค์ ์๋ฒ์์ ์ํ๋๋ ๋ชจ๋ thread์ ๊ณต์ ๋์ด ์๋ค. MySQL์ ๋ฉ๋ชจ๋ฆฌ ์ด ์ฉ๊ณผ ๊ด๋ จ๋จ. ๏ MySQLโs internal buffers ๋ฐ caches๋ฅผ ํตํด ๊ฐ๊ฐ์ task์ ์ ์ ํ ํ ๋น๋์๋์ง ํ์ธ. โ key buffer = MyISAM indexes๊ฐ ๋ณด๊ด๋๋ ๋ฉ๋ชจ๋ฆฌ ์ฅ์. โ Index block์ด ์ด์ฉ๋ ๋ ์ด๋ค์ buffer๋ก load๋จ. ๏ query ์ํ ์ ํด๋น index block์ด buffer์ ์์ผ๋ฉด ๊ฑฐ๊ธฐ์ ์ฝ๊ณ , ์์ผ๋ฉด disk์์ keybuffer๋ก load์ํจ๋ค (๋ฐ๋ผ์ ๋ฆ๋ค). ์ผ๋ฐ์ ์ผ๋ก key buffer๋ ํด ์๋ก ์ข๋ค. โข key_buffer_size์ ๊ฒฐ์ ๏ ๋ฉ๋ชจ๋ฆฌ ํฌ๊ธฐ, ์๋ฒ๊ฐ dedicated MySQL server ์ธ์ง ์ฌ๋ถ, index data์ ํฌ๊ธฐ (์ฆ, how big your .MYI files are in total). โ Jeremy Zawodny๋ dedicated์๋ฒ ์ด ๋ฉ๋ชจ๋ฆฌ์ 20% ~ 50% ๊ถ์ฅ. shared machine์ ๊ฒฝ์ฐ ๋ ์ ๊ฒ ์ค์ ! ๋ํ index data๊ฐ ์์ ๋๋ ์ ๊ฒ ์ค์ . If you have only 20MB of index data, there is little point in allocating 128MB to the key buffer. โข (์ฃผ์) key buffer๋ ๋จ์ง MyISAM tables์ ์ํ ๊ฒ์ด๋ฏ๋ก ๋ค๋ฅธ table type ์๋ ๋ค๋ฅธ parameter ์ ์ฉํ ๊ฒ. (์: InnoDB table๋ง ์ฌ์ฉ ์์๋ innodb_buffer_pool_size๋ฅผ ์กฐ์ . ๏ InnoDB buffer pool stores both index and table data.) โ table cache์ ๋ฌธ์ - controlled via the table_cache option. โข ๋์์ open ๋ ์ ์๋ ํ ์ด๋ธ์ ์ต๋ ๊ฐ์๋ฅผ ํ์ . (์ฆ, MyISAM table์ ๊ฒฝ ์ฐ, ๊ฐ๊ฐ์ ํ ์ด๋ธ๊ณผ ์ธ๋ฑ์ค๋ OS์์์์ ๊ฐ๋ณ์ ์ธ ํ์ผ) Opening and closing files is slow, so these files are left open until they are explicitly closed, the server shuts down, or the total number of open tables exceeds the table_cache parameter.๏ table์ ์ซ์๊ฐ ๋ง์ ๋๋ table_cache ๊ฐ์ ์ฆ๊ฐ์ํค๋ฉด ์ข๋ค. (๋ํ OS์ ๋ฐ๋ผ open file์ ์ ๋๋ single process/user ๋น ๊ฐ๋ฅํ open file์ ์๊ฐ ํ์ ๋๋ฏ๋ก table_cache 185 ๊ฐ์ resetํ๊ธฐ ์ ์ ์ดํด ๋ณผ ๊ฒ) โข (์ด์ธ์๋) ๋ค์ํ chunks of memory allocated on a perthread basis โข The value is the same for each thread, but each thread can have this amount of memory allocated to the specified purpose. โ read buffer size, controlled by the read_buffer_size parameter, โข ํ ์ด๋ธ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ธฐ ์ํด full table scan ํ ๋ ์ฌ์ฉ. ๋ณด๊ด๋๋ table data๊ฐ ๋ง์ ์๋ก disk read๋ ์์์ง๋ค. ๋จ, ์์นซ ๋๋ฌด ํฌ๋ฉด ๊ฐ ๊ฐ์ thread์ ๋ํ read buffer๊ฐ ๋๋ฌด ๋ง์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์๋นํ ์๋ ์๋ค. (You may want to note that this parameter was previously called the record buffer and was controlled by the record_buffer parameter.) โ The sort buffer, controlled by the sort_buffer parameter, โข is used when you run queries containing ORDER BY clauses. 186 Tuning Other Factors โข tips โข MySQL recommends Solaris (ํนํ multiprocessor์ฌ์ฉ ์) โข Multiple disk ์ฌ์ฉ ์ ๊ฐ๊ฐ์ database์ ์ ํฉํ disk ์ฌ์ฉ. โ RAIDโRAID 0 will improve reading and writing performance, and RAID 1 or 5 will improve reading performance. โข Consider use of a journaling file system, such as Reiserfs or XFS. โข Fast networks when using replication. 187 Chapter 18. Optimizing Your Database โข ์ผ๋ฐ์ ์ธ database design guidelines and normalization + โข What's slow in MySQL databases? โข Making the right design choices โข Using indexes for optimization โข Using OPTIMIZE TABLE 188 What's Slow in MySQL Databases? โข Server optimize ํ ๋ค์ ์ฌํญ ๊ฒํ : โ Not using enough indexes. โข ๊ฐ์ฅ ํํ ๋ฌธ์ = tables that have no indexes or that are without indexes on columns you are searching. โข ๊ทธ๋ ๋ค๊ณ index๊ฐ ๋ง์ ์๋ก ์ข์ ๊ฒ์ ์๋๋ค. ๏ โ Using too many indexes. โข If you are retrieving data, indexes are good. โข When you are inserting new rows, updating rows, or deleting rows, indexes are no longer your friends. When you update data, the indexes need updating too, increasing the amount of overhead you have to deal with. โ Using table- and column-level privileges. โข ๋ง์ resource์ table- or column-level privileges ์ค์ ํ๋ฉด MySQL์ด ์ด๋ฅผ query์๋ง๋ค ํ์ธํด์ผ ํ๋ค. โ Making the wrong database design choices. โข โฆ 189 Making the Right Design Choices โข Use the smallest type that data will fit in. โ ์: storing numbers of 1 ~10: INT ๋์ TINYINT ์ฌ์ฉ. โ Row์ table์ด ์์ ์๋ก ๊ฒ์์ด ๋น ๋ฅด๋ค. + ๋ฐ์ดํฐ๊ฐ ์ ์ ์๋ก ๋ ๋ง์ row๋ฅผ cache. โข Use fixed-length records where possible. โ โฆ โ no VARCHAR, no TEXT, and no BLOB. โข โข If you need to store TEXT and BLOB, you might consider denormalizing your schema to break the TEXT or BLOB fields out into a separate table. VARCHAR๋ง ์ฌ์ฉํ๋ ๊ฒฝ์ฐ CHAR๋ก ๋ณํ์ ๊ฒํ . โ = a trade-off with more space on disk, against suggestion above โข Declare as many columns NOT NULL as possible. โ If your data logically requires NULL values, then obviously you should use them. ๋จ, small speed and storage space price for NULL. โข Choose the table type on a table-by-table basis. โ Non-transaction-safe tables (MyISAM) involve a lot less overhead ๏ faster than the transaction-safe types (InnoDB and BDB). โข โข Choose appropriate indexes. ๊ทน๋จ์ ์ธ ๊ฒฝ์ฐ even consider denormalization of tables to reduce the number of joins made for common queries. โ ๋จ, ๊ด๋ฆฌ๊ฐ ์ด๋ ค์์ง ์ ์๊ธฐ ๋๋ฌธ์ ๋งค์ฐ ์กฐ์ฌํด์ ๊ฒฐ์ ํ ์ฌํญ. 190 Indexing for Optimization โข ๊ฐ์ โ check if database has any indexes. (๏ DESCRIBE ๋ช ๋ น์ด) โข index = a lookup table to find specific rows in a table quickly. โ Indexes in MySQL are stored as b-trees โ can be on a single column or can span multiple columns (just like keys). An index will be used when running a query, if the search is being performed on the following: โข A single column that has a single-column index. ์: if we index departments on departmentID and perform a query like SELECT...WHERE departmentID=n. โข A set of columns that forms a multicolumn index. ์: if we have created an index on the employee.assignment table on (clientID, employeeID, workdate) and we perform a query like SELECT...WHERE clientID=x AND employeeID=y AND workdate=z. โข A column or set of columns that forms a subset of a multicolumn index, as long as there is a leftmost prefix of the index columns. ์: with the assignment table as before, with an index on (clientID, employeeID, workdate), indexes would be used for these types of queries: โข SELECT...WHERE clientID=x โข SELECT...WHERE clientID=x AND employeeID=y โ But, they would not be used for this type: โข SELECT...WHERE employeeID=y AND workdate=z โ (ํ๋ ๋๋ ์ฌ๋ฌ column์ ๋ํด) queries that does not fit the preceding criteria๊ฐ ๋ง์ ๊ฒฝ์ฐ, run CREATE INDEX statement to create an 191 appropriate index. Note that MySQL can use only one index per table in a single query. It cannot combine existing indexes automatically. ANALYZE TABLE โข use the ANALYZE TABLE statement to review and store the key distribution in a table. โ MySQL stores this information and uses it to decide how to execute joins. โข analyze table tablename ; 192 Using OPTIMIZE TABLE โข = MySQL equivalent of defragmenting your hard disk. โข OPTIMIZE TABLE tablename; โ use OPTIMIZE TABLE periodically โฆ โ ๏ ์คํ ๋ฆฌ์ง๋ฅผ ์ ์ ๋ํ๊ณ , re-sort the index, and update statistics for the table. โ MyISAM and BDB tables ์๋ง ์ ์ฉ 193 19. Query ์ต์ ํ โข ๊ฐ๋ณ query ๋ถ์์ ํตํด ์ฑ๋ฅํฅ์ ๊ฐ๋ฅ. โข In this chapter: โ โ โ โ โ โ Finding slow queries Benchmarking your queries Using the slow query log Using EXPLAIN to see how queries are executed Understanding MySQL's built-in query optimization Optimization tips 194 Finding Slow Queries โข ์๊ฐ์ ๋ง์ด ์์ํ๋ ๋ถ๋ถ์ด ์ด๋ ๊ณณ์ธ์ง ์ฐพ๋๋ค. โ Observation: ํํ ํน์ query๊ฐ ๋ฆ๋ค๋ ๊ฒ์ ๋ฐ๊ฒฌ โ Benchmarking: Test your application to see which parts of it are slow. โ Slow query log: This log tracks slow queries, as you might expect from its name. โข ์ผ๋จ ์๊ฐ์ง์ฒด ๋ถ๋ถ์ ํ์ธํ๋ฉด ๊ทธ ์์ธ ๋ฑ์ EXPLAIN ์ ํตํด ๋ถ์ํ๊ณ optimize the query. โข ๋ชจ๋ query๋ฅผ speed up ํ ํ์๋ ์๋ค. ๊ฐ์ฅ ์ํฅ ๋๊ฐ ํฐ ๋ถ๋ถ์ ์ฃผ๋ ฅ. ์๋ชปํ๋ฉด ์์ ์ฑ๋ฅ๊ฐ์ ์ ๋ง ์ ์๊ฐ์ด ์์๋๊ธฐ๋ ํ๋ค. 195 Benchmarking Your Queries โข Benchmarking = timing how long your queries take. โ by running a query many times โฆ โข ๏ A single execution of the query will be subject to load issues โข ๋ํ 2๋ฒ์งธ๋ก ์ค์ํ๋ฉด query์ํ์ด ๋นจ๋ผ์ง๋ค. ๏ the query is cached. โ ๋ํ external scripts or programs ๋ฅผ ์ด์ฉํ๊ธฐ๋ ํจ. โข ์: download the source distribution of MySQL and look at the benchmarking code that is included in the sql-bench directory. โ ๋ํ built-in BENCHMARK() function ์ค์ โข ์: select benchmark(1000000, 6*9); ๏จ +-----------------------------------+ | benchmark(1000000, 6*9) | +-----------------------------------+ | 0 | +-----------------------------------+ 1 row in set (0.25 sec) โข /* 2 parameters: the number of times to evaluate the expression (์ฌ๊ธฐ์๋ 1๋ฐฑ ๋ง) and the expression we want to evaluate (์ฌ๊ธฐ์๋ six times nine). */ โข BENCHMARK() function ๊ฒฐ๊ณผ๊ฐ์ ํญ์ 0์ด๋ฏ๋ก ์๋ฏธ ์๊ณ ๋์ query ์ํ์๊ฐ์ด ์ค์. (์ฌ๊ธฐ์๋ evaluating 6x9 one million times took a quarter of a second.) โ ๋ํ pass BENCHMARK() a query, ์: select benchmark(10000000, 'select employee.name, department.name from employee, department where 196 employee.departmentID=department.departmentID'); Using the Slow Query Log โข (๋ชฉ์ ) ์ด๋ค query๊ฐ ๋ฆ์์ง ์ถ์ (track) (๋จ์: ์๊ฐ) โข (๋ฐฉ๋ฒ) turn on slow query logging with the --log-slowqueries=filename option when starting the MySQL server or in your configuration file. โ If you also turn on the --log-long-format option, all queries that run without using an index are also logged. This can help you to see where you should be targeting your optimization efforts. โ You can define what is meant by a slow query by using the long_query_time variable. You can set this in your configuration file or by using the SET command. This variable is in seconds. โ slow query log๋ text file์ด๋ฏ๋ก ์ง์ ๋ณผ ์ ์๋ค. Summary๋ง ๋ณผ ์๋ ์๋ค. ๏ by running the mysqldumpslow script (in the scripts directory of your MySQL installation. ๋ํ Perl script์ด๋ฏ๋ก Windows์์๋ Perl ์ค์น ํ์) โข (ํ๊ณ) you cannot configure it to log slow queries that take less than one second. The administrator might want to be informed when queries take more than one-tenth of a second or some other fraction. ๏ future version. 197 Using EXPLAIN to See How Queries Are Executed โข ์: explain select e.name, d.name from employee e, department d where e.departmentID = d.departmentID; ๏จ +----+-------------+-------+--------+---------------+--------------+-----------+-----------------------+------+--------+ | id | select_type | table | type | possible_keys| key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+--------------+-----------+-----------------------+------+--------+ | 1 | SIMPLE |e | ALL | NULL | NULL | NULL | NULL | 5 | | | 1 | SIMPLE |d | eq_ref | PRIMARY | PRIMARY | 4 | e.departmentID | 1 | | +----+-------------+-------+--------+----------------+-------------+------------+----------------------+------+--------+ 2 โข โข โข โข โข โข โข โข โข โข โข rows in set (0.00 sec) /* table๋น ํ๋์ row. Row์ ์์ = table์ด join๋ ์์. id = a sequence number. (์์ปจ๋ subquery์ฌ ์ฉ์, each SELECT is numbered.) select_type =(๋๋ถ๋ถ์ SIMPLE (a plain vanilla SELECT). subqueries ์ฌ์ฉ ์์๋, the outer query ๊ฐ PRIMARY, inner queries๊ฐ SUBSELECT or DEPENDENT SUBSELECT) table This is the table this row is about. type ; tells you how the table is being joined to the other tables in the query. possible_keys ; ์ด๋ค index๊ฐ ์ด์ฉ๋ ์ ์์๋์ง ํ์ (relevant indexes ๊ฐ ์์ผ๋ฉด NULL) key ; query์ ์ฌ์ฉ๋ index ํ์. (NULL if no index was selected) key_len = the length of the index MySQL decided to use. ref = the value being compared to the key to decide whether to select rows. rows = an estimate of the number of rows from this table MySQL will read to generate the results of the query. You can work out how many rows will be read overall by multiplying the rows' values together. This gives a basic benchmark for how fast the query will run. Extra = ์ถ๊ฐ์ ๋ณด (์: Using index means that MySQL can retrieve the result of the query completely from an index without reading data from the table.) (ํด์ ๋ท์ฅ) 198 โ โ Employee table์์์ join type ALL; ๋ชจ๋ row๋ค์ด scan๋ ๊ฒ์ ์๋ฏธ.๏ table์ ๋ฐ์ดํฐ๊ฐ ๋ง์ผ๋ฉด ๋ฆ์ด์ง๊ฒ. ์ค์ ๋ก join type ALL์ ์ต์ ์ ๊ฒฝ์ฐ. (๏ typically if a table has no useful index.) (ํด๊ฒฐ์ฑ ) add an index. Department์ ํด๋น๋๋ row์ join type eq_ref; (์๋ฏธ) a single row will be read from the department table for each row in the employee table. (= one of the best types.) The only better values for type are system and const, (์๋ฏธ: table์ด ์ค์ง ํ๋์ matching row๋ฅผ ๊ฐ์ง๋ฉฐ can effectively be treated as a constant. ) โ (other possible values for type: ) โข ref ; All rows with matching index values will be read from the table. (eq_ref ๋ค์์ second best)๋ก์ non-unique key ์ํ์ผ ๋์. โข range ; (์๋ฏธ) all rows in a particular range will be read from the table. (eq_ref ๋๋ ref ๋ง๋ ๋ชป ํจ) โข index ; (์๋ฏธ) the complete index will be scanned. (ALL๋ณด๋ค๋ ์ข์ง๋ง ์์์ ๋ค๋ฅธ ๊ฒ๋ณด๋ค ๋ชปํจ.) This is preferable to scanning the complete table, but is far from ideal. โข possible_keys and key ; The department table has one option: PRIMARY. Employee table has the value NULL in both of these columns, (์๋ฏธ: there's no key to use and therefore no key will be used. = a strong hint that we should be adding another index! โ ์ด ์ ๋ณด์ ๋ฐ๋ผ ๋ค์๊ณผ ๊ฐ์ด ์ถ๊ฐ index ์์ฑ ๏ create index ename_did on employee(name, departmentID); โข If we then rerun EXPLAIN, we get the following output: +----+-------------+-------+---------+-------------------+---------------+-----------+---------------------+------+---------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+---------+-------------------+--------------+------------+---------------------+------+---------------+ | 1 | SIMPLE |e | index | NULL | ename_did | 85 | NULL | 5 | Using index | | 1 | SIMPLE |d | eq_ref | PRIMARY | PRIMARY | 4 | e.departmentID | 1| | +----+-------------+------+----------+-------------------+---------------+----------+----------------------+------+---------------+ 2 rows in set (0.00 sec) โข /* employee์ type์ index (๏ ์ด์ ์ ํฉํ index๋ฅผ ๊ฐ์ง๋ฏ๋ก) The new index is listed as a possible key, but it is not actually being used. Under Extra you will see that only the index for this table is used, rather than the table itself. This should be slightly faster. โข (EXPLAIN ; query์๋์ฆ์ง์ ์ํด index๋ฅผ ์ด๋ป๊ฒ ํ์ฉํ ์ง ์๋ ค ์ค.) 199 Understanding MySQL's Built-In Query Optimization โข MySQL applies many optimization rules to queries. โ MySQL uses its estimated number of rows (as shown in EXPLAIN) to work out the best order in which to join tables. If you notice that its estimate is off, you may want to experiment with using a STRAIGHT JOIN to force the table order. Benchmarking before and after cases will tell you whether you are helping or hindering. โ To choose an index, MySQL looks for the most relevant index that spans less than 30% of the rows. If it can't find an index fitting these criteria, the table will be scanned instead. (This was what happened in the EXPLAIN query we looked at earlier, after we added the new index.) โ Expressions in WHERE clauses are optimized in a similar way to the way many programming compilers optimize expressions. For example, unnecessary parentheses in expressions are removed. This is one reason you should feel free to make your queries more readable with parentheses. โ If a query can be resolved wholly from indexes, it will be done without any reference to the actual rows in the table. Evaluation of COUNT(*) is also evaluated without reading or counting the rows in a table because this data is stored separately. โข Manual, source code ๋ถ์ํ ๊ฒ !! 200 Optimization Tips โข Add indexes. โ Chapter 18, "Optimizing Your Database." โ Remember though that although an appropriate index might speed up operations that need to find data in the table, keeping indexes up-to-date increases the time required to write data. Do not add indexes that will not be used. โข Use ANALYZE TABLE. โ (See Chapter 18 for syntax.) โ This updates the information MySQL stores about key distribution. This information is used to decide the order in which tables are joined. If MySQL seems to be joining your tables in a strange order, try ANALYZE TABLE. โข Use OPTIMIZE TABLE. โ (See Chapter 18 for syntax.) โ This defragments the table storage, sorts the indexes, and updates the table statistics as used by the query optimizer. 201