Mysql Tutorial 1

download Mysql Tutorial 1

of 40

Transcript of Mysql Tutorial 1

  • 7/29/2019 Mysql Tutorial 1

    1/40

    May 26, 2005 MySQL Tutorial - 1 1

    MySQL Tutorial 1How to Use MySQL

    CSCI 2140

    TA: Jiye [email protected] 26, 2005

    http://flame.cs.dal.ca/~jiye/CSCI2140/

    mailto:[email protected]:[email protected]
  • 7/29/2019 Mysql Tutorial 1

    2/40

    May 26, 2005 MySQL Tutorial - 1 2

    Agenda Getting familiar with

    our network system

    Introducing MySQL

    SQL basics

    create, add, select, modify, delete Exercises (see handout)

  • 7/29/2019 Mysql Tutorial 1

    3/40

    How to Login to MySQL D:\Documents and Settings\alumno>cd D:\Archivos de programa\MySQL\MySQL Server 5.0\bin

    D:\Archivos de programa\MySQL\MySQL

    Server 5.0\bin>mysql -u rootproot

    mysql>

    May 26, 2005 MySQL Tutorial - 1 3

  • 7/29/2019 Mysql Tutorial 1

    4/40

    May 26, 2005 MySQL Tutorial - 1 4

    How to get a UNIX account Sun workstation or ssh program (putty)

    Log into torch.cs.dal.ca

    Username: discover

    Passwd: query

    Enter your student number

    Ask Help Desk

  • 7/29/2019 Mysql Tutorial 1

    5/40

    May 26, 2005 MySQL Tutorial - 1 5

    How to get a Windows account Username: the same as torch account

    Password: student ID number. Dontforget B is capitalized.

  • 7/29/2019 Mysql Tutorial 1

    6/40

    May 26, 2005 MySQL Tutorial - 1 6

    What is MySQL? MySQL is a database management

    system (DBMS) for relational databases

    Online Manual http://dev.mysql.com/doc/

    MySQL is installed on torch

    Each user ID stands for a database Create tables under this database

  • 7/29/2019 Mysql Tutorial 1

    7/40May 26, 2005 MySQL Tutorial - 1 7

    How to Login to MySQL Go on torch.cs.dal.ca

    Run mysql to login

    torch: ~$ mysql -p

    Enter password:

    Welcome to the MySQL monitor. Commands end with ; or \g.

    Your MySQL connection id is 123943 to server version: 4.0.12

    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

    mysql>

    Student ID

    Lower case

  • 7/29/2019 Mysql Tutorial 1

    8/40May 26, 2005 MySQL Tutorial - 1 8

    How to Logout Use the command exit or quittorch: ~$ mysql -p

    Enter password:Welcome to the MySQL monitor. Commands end with ; or \g.

    Your MySQL connection id is 123975 to server version: 4.0.12

    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

    mysql> exit

    Bye

    torch: ~$

  • 7/29/2019 Mysql Tutorial 1

    9/40May 26, 2005 MySQL Tutorial - 1 9

    Use your databaseAfter login MySQL, use your own

    database before creating tables

    torch: ~$ mysql -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 125213 to server version: 4.0.12

    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

    mysql> use jiye;Database changedmysql>

    Your user ID

  • 7/29/2019 Mysql Tutorial 1

    10/40May 26, 2005 MySQL Tutorial - 1 10

    SQL Basics Suppose we would like to create a few

    tables, such as employee table,

    employer table and payment table,representing a database aboutemployee information.

  • 7/29/2019 Mysql Tutorial 1

    11/40May 26, 2005 MySQL Tutorial - 1 11

    How to write commands in MySQL How to create a table

    Primary Keys and Foreign Keys

    How to add records

    How to select records

    How to modify records

    How to delete records

  • 7/29/2019 Mysql Tutorial 1

    12/40May 26, 2005 MySQL Tutorial - 1 12

    DDL: How to create tables Use create

    create table (column_name data_type [not null] ,column_name data_type [not null],primary key (column_name));

    To show the structure of the table

    describe ;

  • 7/29/2019 Mysql Tutorial 1

    13/40May 26, 2005 MySQL Tutorial - 1 13

    Examplemysql> create table employee(

    empno smallint(4) not null auto_increment,

    name char (8) not null,

    job char (4) ,

    salary int (8) not null,

    deptno int (4) not null,primary key (empno)

    );

  • 7/29/2019 Mysql Tutorial 1

    14/40

    May 26, 2005 MySQL Tutorial - 1 14

    Primary Key Primary Key is a column or set of

    columns

    Uniquely identifies the rest of the datain any given row.

    For Example: in the employee table,employee number is the primary key.

  • 7/29/2019 Mysql Tutorial 1

    15/40

    May 26, 2005 MySQL Tutorial - 1 15

    Foreign KeyA foreign key is a column in a table This column is a primary key of another

    tableAny data in a foreign key column must

    have corresponding data in the othertable

    http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constraints.html

  • 7/29/2019 Mysql Tutorial 1

    16/40

    May 26, 2005 MySQL Tutorial - 1 16

    Foreign Key The goal of using foreign keys is that,

    tables can be related without repeatingdata

    Note that foreign keys in SQL are usedto check and enforce referentialintegrity, not to join tables. If you want

    to get results from multiple tables froma SELECT statement, you do this byperforming a join between them:

    SELECT * FROM t1, t2 WHERE t1.id = t2.id;

  • 7/29/2019 Mysql Tutorial 1

    17/40

    May 26, 2005 MySQL Tutorial - 1 17

    employer

    Example Create table with

    foreign keyscreate table employee2(

    empno smallint(4) not null,

    salary float,

    primary key (empno)

    ) Engine = innodb;

    create table employer (id smallint(4),employee_no smallint(4),

    index employ_ind (employee_no),foreign key(employee_no)references employee2(empno)on delete cascade) Engine=innodb;

    empno(PK)

    salary

    100 200.85

    200 129.54

    300 98.17

    id employee_no(FK)

    51 100

    52 100

    53 200

    54 300

    employee2

  • 7/29/2019 Mysql Tutorial 1

    18/40

    May 26, 2005 MySQL Tutorial - 1 18

    The Syntax of a Foreign Key

    Constraint Definition[CONSTRAINT [symbol]] FOREIGN KEY

    (index_col_name, ...) REFERENCES table_name(index_col_name, ...) [ON DELETE {CASCADE | SET

    NULL | NO ACTION | RESTRICT}] [ON UPDATE{CASCADE | SET NULL | NO ACTION | RESTRICT}]

    Both tables have to be InnoDB type

    InnoDB provides MySQL with a transaction-safestorage engine with commit, rollback, and crashrecovery capabilities.

    http://dev.mysql.com/doc/mysql/en/innodb-overview.html

    http://dev.mysql.com/doc/mysql/en/innodb-overview.htmlhttp://dev.mysql.com/doc/mysql/en/innodb-overview.htmlhttp://dev.mysql.com/doc/mysql/en/innodb-overview.htmlhttp://dev.mysql.com/doc/mysql/en/innodb-overview.htmlhttp://dev.mysql.com/doc/mysql/en/innodb-overview.html
  • 7/29/2019 Mysql Tutorial 1

    19/40

    May 26, 2005 MySQL Tutorial - 1 19

    The Syntax of a Foreign Key

    Constraint Definition InnoDB rejects any INSERT or UPDATE operation that

    attempts to create a foreign key value in a child tablewithout a matching candidate key value in the parent table. CASCADE: Delete or update the row from the parent table and automatically delete

    or update the matching rows in the child table. SET NULL: Delete or update the row from the parent table and set the foreign key

    column(s) in the child table to NULL. This is only valid if the foreign key columns donot have the NOT NULL qualifier specified.

    NO ACTION: NO ACTION means no actionin the sense that an attempt to delete orupdate a primary key value will not be allowed to proceed if there is a relatedforeign key value in the referenced table.

    RESTRICT: Rejects the delete or update operation for the parent table. NO ACTIONand RESTRICT are the same as omitting the ON DELETE or ON UPDATE clause.(Some database systems have deferred checks, and NO ACTION is a deferred check.In MySQL, foreign key constraints are checked immediately, so NO ACTION andRESTRICT are the same.)

    SET DEFAULT: This action is recognized by the parser, but InnoDB rejects tabledefinitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULTclauses.

  • 7/29/2019 Mysql Tutorial 1

    20/40

    May 26, 2005 MySQL Tutorial - 1 20

    MySQL Table Types If we want to use Foreign Key

    InnoDB tables

    Otherwise Default table type, MyISAM

    In SQL queries you can freely mix

    InnoDB type tables with other tabletypes of MySQL, even within the samequery.

  • 7/29/2019 Mysql Tutorial 1

    21/40

    May 26, 2005 MySQL Tutorial - 1 21

    How to add records Use insert

    insert into values

    (column_value, , column_value);

  • 7/29/2019 Mysql Tutorial 1

    22/40

    May 26, 2005 MySQL Tutorial - 1 22

    Exampleinsert into employee values (1000,'Wilson','Clrk',1700,10);

    insert into employee values (1001,'Smith','Slsm',2500,40);

    insert into employee values (1003,'Reed','Anlt',3500,30);

    insert into employee values (1005,'Watson','Mngr',4500,30);

    insert into employee values (1009,'Allen','Mngr',3800,40);

    insert into employee values (1010,'Turner','Clrk',1800,50);

    insert into employee values (2000,'Chen','Mngr',2900,10);insert into employee values (2100,'Ramirez','Mngr',3650,50);

    insert into employee values (2130,'McDonnel','Clrk',1625,60);

    insert into employee values (2140,'Simpson','Drvr',825,60);

  • 7/29/2019 Mysql Tutorial 1

    23/40

    May 26, 2005 MySQL Tutorial - 1 23

    Example On Slide 17

    insert into employee2 values (100, 200.85);insert into employee2 values (200, 129.54);insert into employee2 values (300, 98.17);

    insert into employer values (51, 100);insert into employer values (52, 100);

    insert into employer values (53, 200);insert into employer values (54, 300);

  • 7/29/2019 Mysql Tutorial 1

    24/40

    May 26, 2005 MySQL Tutorial - 1 24

    How to Select Records select * from ;

    select * from where = ;

    select * from where = order by;

    select from

    ; select from

  • 7/29/2019 Mysql Tutorial 1

    25/40

    May 26, 2005 MySQL Tutorial - 1 25

    Example

    select * from employee;

    select * from employee where empno = 1000;select * from employee where job = 'Clrk' order by salary;

    select name, empno from employee;

    select job from employee;

    select distinct job from employee;

  • 7/29/2019 Mysql Tutorial 1

    26/40

    May 26, 2005 MySQL Tutorial - 1 26

    Example On Slide 17

    select empno from employee2;

    select empno from employee2where salary >=50 and salary < 150;

    select * from employee2, employer;select id, empno from employer m, employee2 n

    where m.employee_no = n.empno;

  • 7/29/2019 Mysql Tutorial 1

    27/40

    May 26, 2005 MySQL Tutorial - 1 27

    How to Modify Records Use update to modify attribute values

    of (some) tuples in a table

    update set = , , = [where ];

  • 7/29/2019 Mysql Tutorial 1

    28/40

    May 26, 2005 MySQL Tutorial - 1 28

    Example

    update employee set job = Drvr, deptno = 20 , salary =

    salary + 1000 where name = 'Reed;

    update employee set salary = salary * 1.15 where

    deptno in (10, 40);

  • 7/29/2019 Mysql Tutorial 1

    29/40

    May 26, 2005 MySQL Tutorial - 1 29

    How to Delete Records Use delete

    delete from [where

    ];

  • 7/29/2019 Mysql Tutorial 1

    30/40

    May 26, 2005 MySQL Tutorial - 1 30

    Example

    delete from employee where

    salary < 2000;

    delete from employee;

    Note: this command will delete all therecords in the employee table.

  • 7/29/2019 Mysql Tutorial 1

    31/40

    May 26, 2005 MySQL Tutorial - 1 31

    Tip1: How to Load Command Execute a SQL script file.

    Take a file name as an argument.

    Save SQL commands into a file

    Execute the commands:

    mysql> source ;

  • 7/29/2019 Mysql Tutorial 1

    32/40

    May 26, 2005 MySQL Tutorial - 1 32

    Example In file temp.sql

    select * from employee;

    select name from employee wheresalary < 3000;

    mysql> source temp.sql;

  • 7/29/2019 Mysql Tutorial 1

    33/40

    May 26, 2005 MySQL Tutorial - 1 33

    Tip2: How to Save Results Save results

    tee

    Set outfile. Append everything into givenoutfile . All the information displayedon screen is stored in .

  • 7/29/2019 Mysql Tutorial 1

    34/40

    May 26, 2005 MySQL Tutorial - 1 34

    Examplemysql>tee result;mysql> select * from employee;mysql> notee;mysql> exit

    torch: ~$ cat resultmysql> select * from employee;

    EMPNO NAME JOB SALARY DEPTNO---------- -------- ---- ---------- ----------

    1000 Wilson Clrk 1720 10

    1001 Smith Slsm 2500 40

    10 rows selected.mysql> notee;torch: ~$

  • 7/29/2019 Mysql Tutorial 1

    35/40

    May 26, 2005 MySQL Tutorial - 1 35

    Appendix: MySQL Data TypesType Size Descriptiontinyint[Length] 1 byte Range of128 to

    127

    float 4 bytes A small number witha floating decimalpoint

    Date 3 bytes In the format of

    YYYY-MM-DD

    Time 3 bytes In the format ofHH:MM:SS

    varchar[Length] String length + 1byte

    A fixed-length fieldfrom 0 to 255characters long

  • 7/29/2019 Mysql Tutorial 1

    36/40

    May 26, 2005 MySQL Tutorial - 1 36

    Appendix: MySQL under UnixA few commands

    use username;

    show tables;

    show columns from employee;

    help;

    exit; SQL commands (select, insert, delete,)

  • 7/29/2019 Mysql Tutorial 1

    37/40

    May 26, 2005 MySQL Tutorial - 1 37

    Appendix: MySQL under UnixA few commands

    SHOW DATABASES

    use mysql

    SHOW VARIABLES;

    SHOW VARIABLE LIKE 'a%;

    CREATE DATABASE PRACTICA1 CREATE SCHEMA PRACTICA2

    DESCRIBE EMPLOYEE;

    SHOW CREATE TABLE EMPLOYEE

  • 7/29/2019 Mysql Tutorial 1

    38/40

    Appendix: MySQL under Unix SELECT @@ROWCOUNT mysql> SELECT

    SQL_CALC_FOUND_ROWS * FROMmy_table;

    mysql> SELECT FOUND_ROWS();

    May 26, 2005 MySQL Tutorial - 1 38

  • 7/29/2019 Mysql Tutorial 1

    39/40

    May 26, 2005 MySQL Tutorial - 1 39

    Appendix: MySQL Control Center Graphical user interface (GUI) to the

    MySQL database server

    Supports interactive use, includingsyntax highlighting and tab completion

    Download from

    http://dev.mysql.com/downloads/other/mysqlcc.html

    d l

  • 7/29/2019 Mysql Tutorial 1

    40/40

    Appendix: MySQL Control Center

    Student ID