Você está na página 1de 23

1. Basic MySQL Tutorial A.

Manage Database in MySQL Including - creating a new database, Removing an Existing database, Selecting a database to work with and listing all databases. Creating Database Before doing anything else with the data, you need to create a database. In MySQL, a database is a collection of objects that are used to store and manipulate data such as tables, database views, triggers, stored procedures, etc. CREATE DATABASE [IF NOT EXISTS] database name; Displaying Databases SHOW DATABASES; Selecting a database to work with Before working with a particular database, you must tell MySQL which database you want to work with by using the USE statement. USE database_name; From now all operations such as querying data, create new tables or stored procedures which you perform, will take effects on the current database Removing Databases

Removing database means you delete the database physically. All the data and related objects inside the database are permanently deleted and this cannot be undone, therefore it is very important to execute this query with extra cautions.

To delete a database, you use the DROP DATABASE statement as follows: DROP DATABASE [IF EXISTS] database_name;

Followed the DROP DATABASE is the database name that you want to remove. Similar to the CREATE DATABASE statement, the IF EXISTS is an optional part of the statement to prevent you from removing a database that does not exist in the database server.

If you want to practice with the DROP DATABASE statement, you can create a new database, make sure that it is created and remove it. Take a look at the following queries: 1 CREATE DATABASE IF NOT EXISTS temp_database; 2 SHOW DATABASES; 3 DROP DATABASE IF EXISTS temp_database;

B. Understanding MySQL Table Types, or Storage Engines Summary: in this tutorial, you will learn various MySQL table types, or storage engines. It is essential to understand the features of each table type in MySQL so that you can use them effectively to maximize the performance of your databases.

MySQL provides various storage engines for its tables as below:

MyISAM InnoDB MERGE MEMORY (HEAP) ARCHIVE CSV FEDERATED

MySQL supports several storage engines that act as handlers for different table types. MySQL storage engines include both those that handle transaction-safe tables and those that handle nontransactionsafe tables.

Note Prior to MySQL 5.1.38, the pluggable storage engine architecture is supported on Unix platforms only and pluggable storage engines are not supported on Windows. To determine which storage engines your server supports by using the SHOW ENGINES statement.

The value in the Support column indicates whether an engine can be used. A value of YES, NO, or DEFAULT indicates that an engine is available, not available, or available and currently set as the default storage engine. mysql> SHOW ENGINES\G *************************** 1. Row *************************** Engine: FEDERATED Support: NO Comment: Federated MySQL storage engine Transactions: NULL XA: NULL Savepoints: NULL *************************** 2. row *************************** Engine: MRG_MYISAM Support: YES Comment: Collection of identical MyISAM tables Transactions: NO XA: NO Savepoints: NO

*************************** 3. Row *************************** Engine: MyISAM Support: DEFAULT Comment: Default engine as of MySQL 3.23 with great performance Transactions: NO XA: NO Savepoints: NO

Each storage engine has its own advantages and disadvantages. It is crucial to understand each storage engine features and choose the most appropriate one for your tables to maximize the performance of

Change engine for table Alter table `information_schema`. `CHARACTER_SETS` engine = MyISAM

Constraints Primary Key-The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key. Foreign Key-Relation Between two tables-establish a link between the data in two tables. NOT NULL - Indicates that a column cannot store NULL value UNIQUE - Ensures that each row for a column must have a unique value CHECK - Ensures that the value in a column meets a specific condition DEFAULT - Specifies a default value when specified none for this column Zerofill-When you select a column with type ZEROFILL it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL also implies UNSIGNED. Using ZEROFILL and a display width has no effect on how the data is stored. It affects only how it is displayed. Here is some example SQL that demonstrates the use of ZEROFILL: CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL); INSERT INTO yourtable (x,y) VALUES (1, 1), (12, 12), (123, 123), (123456789, 123456789); SELECT x, y FROM yourtable; Result: x 00000001 00000012 00000123 123456789 y 1 12 123 123456789

UnsignedAll integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from 2147483648 and 2147483647 up to 0 and 4294967295. CREATE TABLE `employees55` ( `Emp_No` INT(11) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT, `Birth_Date` DATE DEFAULT NULL, `First_Name` VARCHAR(14) NOT NULL, `Last_Name` VARCHAR(16) NOT NULL, `Gender` ENUM('M','F') NOT NULL, `Hire_Date` DATE DEFAULT NULL, PRIMARY KEY (`Emp_No`) ) CREATE TABLE dept_emp ( emp_no INT dept_no CHAR(4) from_date DATE to_date DATE KEY (emp_no),

NOT NULL, NOT NULL, NOT NULL, NOT NULL, -- Build INDEX on this non-unique-value column

KEY (dept_no), -- Build INDEX on this non-unique-value column FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE, -- Cascade DELETE from parent table 'employee' to this child table -- If an emp_no is deleted from parent 'employee', all records -- involving this emp_no in this child table are also deleted -- ON UPDATE CASCADE?? FOREIGN KEY (dept_no) REFERENCES departments (dept_no) ON DELETE CASCADE, -- ON UPDATE CASCADE?? PRIMARY KEY (emp_no, dept_no) -- Might not be unqiue?? Need to include from_date ); CREATE TABLE `indextable` ( `card_id` int(10) unsigned zerofill NOT NULL, `card_name` varchar(20) NOT NULL, PRIMARY KEY (`card_name`), UNIQUE KEY `card_id` (`card_id`) )

C. MySQL Data Types

CREATE TABLE `test` ( `sl_no` TINYINT(3) NOT NULL AUTO_INCREMENT, `emp_id` SMALLINT(6) DEFAULT NULL, `job_id` MEDIUMINT(9) DEFAULT NULL, `mobile_no1` VARCHAR(20) DEFAULT NULL, `mobile_no2` VARCHAR(40) DEFAULT NULL, `ctc_salary` DECIMAL(10,0) DEFAULT NULL, `gross_salary` FLOAT DEFAULT NULL, `net_salart` DOUBLE DEFAULT NULL, `PF` BIT(1) DEFAULT NULL, `name` CHAR(50) DEFAULT NULL, `fname` VARCHAR(50) DEFAULT NULL, `code1` BINARY(50) DEFAULT NULL, `code2` VARBINARY(50) DEFAULT NULL,

`photo1` TINYBLOB, `photo2` TINYBLOB, `photo3` MEDIUMBLOB, `photo4` LONGBLOB, `remarks1` TEXT, `remarks12` TINYTEXT, `remarks13` MEDIUMTEXT, `remarks14` LONGTEXT, `joining_date1` DATE NOT NULL, `joining_date2` TIME NOT NULL, `joining_date3` DATETIME NOT NULL, `joining_date4` NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `joining_date5` YEAR(4) NOT NULL, KEY `sl_no` (`sl_no`) )

E. MySQL Sequence

Each table has only one AUTO_INCREMENT column whose data type is typically integer or float which is very rare. The AUTO_INCREMENT column must be indexed, which means it can be either PRIMARY KEY or UNIQUE index. The AUTO_INCREMENT column must have NOT NULL constraint. When you setAUTO_INCREMENT attribute to a column, MySQL will make it NOT NULL for you in case you dont define it explicitly.

CREATE TABLE employees( emp_no INT(4) AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50) )ENGINE = INNODB;

First, insert two new employees into the employees table: INSERT INTO employees(first_name,last_name) VALUES('John','Doe'), ('Mary','Jane');

1 SELECT * FROM employees;

Third, delete the second employee whose emp_no is 2: DELETE FROM employees WHERE emp_no = 2;

Fourth, insert a new employee: INSERT INTO employees(first_name,last_name) VALUES('Jack','Lee');

Because the storage engine of the employees table is InnoDB, it does not reuse the deleted sequence number. The new row has emp_no 3. Fifth, update an existing employee with emp_no 3 to 1: UPDATE employees SET first_name = 'Joe', emp_no = 1 WHERE emp_no = 3; MySQL issued an error of duplicate entry for the primary key. Lets fix it: UPDATE employees SET first_name = 'Joe', emp_no = 10 WHERE emp_no = 3;

Sixth, insert a new employee after updating the sequence number to 10: INSERT INTO employees(first_name,last_name) VALUES('Wang','Lee');

The next sequence number of the last insert is 4, therefore MySQL use 4 for the new row instead of 11.

In this tutorial, you have learned how to use MySQL sequence to generate unique numbers for a primary key column by assigning the column AUTO_INCREMENT attribute.

H. Changing Table Structure Using MySQL ALTER TABLE The ALTER TABLE statement is used to change the structure of existing tables. You can use the ALTER TABLE statement to add or drop column, change data type of column, add primary key, rename table and many more. The following illustrates the ALTER TABLE statement syntax:

ALTER TABLE test ADD PRIMARY KEY(sl_no); ALTER TABLE test DROP PRIMARY KEY,ADD PRIMARY KEY(emp_id); ALTER TABLE test ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (sl_no); ALTER TABLE test ADD COLUMN complete1 DECIMAL(2,1) NULL; ALTER TABLE table_name action1[,action2,] To alter an existing table: First, you specify the table name that you want to change after the ALTER TABLE keywords. Second, you list a set of actions that you want to apply to the table. An action can be anything

such as adding a new column, adding primary key, renaming table, etc. The ALTER TABLE statement allows you to apply multiple actions in a single ALTER TABLE statement, each action is separated by a comma (,). Were going to create a new table named tasks in our sample database. The following is the script for creating the tasks table. CREATE TABLE tasks ( task_id INT NOT NULL , subject VARCHAR(45) NULL , start_date DATE NULL , end_date DATET NULL , description VARCHAR(200) NULL , PRIMARY KEY (task_id) , UNIQUE INDEX task_id_UNIQUE (task_id ASC) );

Changing columns using MySQL ALTER TABLE statement Using MySQL ALTER TABLE statement to set auto-increment attribute for a column

Suppose you want the value of the task_id column to be increased automatically by one whenever youinsert a new record into the tasks table. To do this, you use the ALTER TABLE statement to set the attribute of the task_id column to AUTO_INCREMENT as follows:

ALTER TABLE tasks CHANGE COLUMN task_id task_id INT (11) NOT NULL AUTO_INCREMENT;

You can verify the change by adding some records to the tasks table. INSERT INTO tasks(subject, start_date, end_date, description) VALUES('Learn MySQL ALTER TABLE', Now(), Now(), 'Practicing MySQL ALTER TABLE statement'); INSERT INTO tasks(subject, start_date, end_date, description) VALUES('Learn MySQL CREATE TABLE', Now(), Now(), 'Practicing MySQL CREATE TABLE statement');

And you can query data to see if the value of the task_id column is increased by 1 each time you insert a new record: SELECT task_id, description FROM tasks

Using MySQL ALTER TABLE statement to add a new column into a table

Because of the new business requirement, you need to add a new column called complete to store the percentage of completion for each task in the tasks table. In this case, you can use the ALTER TABLE to add a new column to the tasks table as follows: ALTER TABLE tasks ADD COLUMN complete DECIMAL(2,1) NULL AFTER description;

Using MySQL ALTER TABLE to drop a column from a table

Suppose you dont want to store the description of tasks in the tasks table and you have to remove it. The following statement allows you to remove the description column of the tasks table: ALTER TABLE tasks DROP COLUMN description;

Renaming table using MySQL ALTER TABLE statement

You can use the ALTER TABLE statement to rename a table. Notice that before renaming a table, you should take a serious consideration to see if the change affects both database and application layers.

The following statement rename the tasks table to work_items:

ALTER TABLE tasks RENAME TO work_items; In this tutorial, youve learned how to use the MySQL ALTER TABLE statement to change existing table structure and to rename the table.

I. MySQL DROP TABLE statement syntax In order to remove existing tables, you use the MySQL DROP TABLE statement. The syntax of the DROP TABLE is as follows: DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name] ... [RESTRICT | CASCADE] The DROP TABLE statement removes a table and its data permanently from the database. In MySQL, you can also remove multiple tables using a single DROP TABLE statement, each table is separated by a comma (,).The TEMPORARY flag allows you to remove temporary tables only. It is very convenient to ensure that you do not accidentally remove non-temporary tables.The IF EXISTS addition allows you to hide the error message in case one or more tables in the list do not exist. When you use IF EXISTS addition, MySQL generates a NOTE, which can be retrieved by using the SHOW WARNING statement. It is important to notice that the DROP TABLE statement removes all existing tables and issues an error message or a NOTE when you have a non-existent table in the list.As mentioned above, the DROP TABLE statement only removes table and its data. However, it does not remove specific user privileges associated with the table. Therefore if a table with the same name is recreated after that, the existing privileges will apply to the new table, which may pose a security risk.The RESTRICT and CASCADE flags are reserved for the future versions of MySQL.Last but not least, you must have DROP privileges for the table that you want to remove.

MySQL DROP TABLE example We are going to remove the tasks table that we created in the previous tutorial on creating tables using CREATE TABLE statement. In addition, we also remove a non-existent table to practice with the SHOW WARNING statement. The statement to remove the tasks table and a non-existent table is as follows: DROP TABLE IF EXISTS tasks, nonexistent_table; If you check the database, you will see that the tasks table was removed. You can check the NOTE, which is generated by MySQL because of non-existent table, by using the SHOW WARNING statement as follows: SHOW WARNINGS;

MySQL DROP TABLE LIKE Image you have a lot of tables whose names start with test in your database and you want to save time by removing all of them using a single DROP TABLE statement. Unfortunately, MySQL does not provide the DROP TABLE LIKE statement that can remove tables based on pattern matching like the following: However, there are some workarounds. We will discuss one of them here for your reference. Lets start creating test* tables for the sake of demonstration.

CREATE TABLE IF NOT EXISTS test1( id int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY(id) ); CREATE TABLE IF NOT EXISTS test2 LIKE test1; CREATE TABLE IF NOT EXISTS test3 LIKE test1; CREATE TABLE IF NOT EXISTS test4 LIKE test1; Weve created four tables named test1, test2, test3 and test4 with the same tabl e structure. Suppose you want to remove all test* tables at a time, you can follow the steps below: First, you declare two variables that accept database schema and a pattern that you want to the tables to match:

-- set table schema and pattern matching for tables SET @schema = 'classicmodels'; SET @pattern = 'test%';

Next, you need to build a dynamic DROP TABLE statement: -- build dynamic sql (DROP TABLE tbl1, tbl2...;) SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';') INTO @droplike FROM information_schema.tables WHERE @schema = database() AND table_name LIKE @pattern; Basically, the query instructs MySQL to go to the information_schema table , which contains data on all tables in all databases, and to concatenate all tables in the database @schema (classicmodels ) that matches the pattern @pattern ( test%) with the prefix DROP TABLE. TheGROUP_CONCAT function creates a comma-separated list of tables. Then, we can display the dynamic SQL to verify if it works correctly:

-- display the dynamic sql statement SELECT @droplike;

you can see that it works as expected.

After that, you can execute the statement using prepared statement in MySQL as follows:

-- execute dynamic sql PREPARE stmt FROM @dropcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt;

For more information on MySQL prepared statement, check it out the MySQL prepared statement tutorial.

Putting it all together. -- set table schema and pattern matching for tables SET @schema = 'classicmodels'; SET @pattern = 'test%'; -- build dynamic sql (DROP TABLE tbl1, tbl2...;) SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';') INTO @droplike FROM information_schema.tables WHERE @schema = database() AND table_name LIKE @pattern; -- display the dynamic sql statement SELECT @droplike; -- execute dynamic sql PREPARE stmt FROM @dropcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; So if you want to drop multiple tables that have a specific pattern in a database, you just use the script above to save time. All you need to do is replacing the pattern and the database schema in @patternand @schema variables. If you often have to deal with this task, you can always develop a stored procedure based on the script and reuse the stored procedure in the future. In this tutorial, weve shown you how to use the DROP TABLE statement to remove existing tables in a particular database. We also discussed about a workaround that allows you to use the DROP TABLE statement to remove tables based on pattern matching.

J. MySQL Temporary Table

Summary: in this tutorial, we will discuss about MySQL temporary table and show you how to create, use and drop temporary tables. Introduction to MySQL temporary table In MySQL, a temporary table is a special type of table that allows you to store a temporary result set, which you can reuse several times in a single session. A temporary table is very handy when it is impossible or expensive to query data that requires a single SELECT statement with JOIN clauses. You often use temporary tables in stored procedures to store immediate result sets for the subsequent uses. MySQL temporary tables have some additional features: A temporary table is created by using CREATE TEMPORARY TABLE statement. Notice that theTEMPORARY keyword is added between CREATE and TABLE keywords. MySQL drops the temporary table automatically when the session ends or connection is terminated. Of course, you can use the DROP TABLE statement to drop a temporary table explicitly when you are no longer use it. A temporary table is only available and accessible by the client who creates the table. Different clients can create a temporary table with the same name without causing errors because only the client who creates a temporary table can see it. However, in the same session, two temporary tables cannot have the same name. A temporary table can have the same name as an existing table in a database. For example, if you create a temporary table named employees in the sample database, the existing employeestable becomes inaccessible. Every query you issue against the employees table refers to theemployees temporary table. When you remove the employees temporary table, the permanentemployees table is available and accessible again. Though this is allowed however it is not recommended to create a

temporary table whose name is same as a name of a permanent table because it may lead to a confusion. For example, in case the connection to the MySQL databaseserver is lost and you reconnect to the server automatically, you cannot differentiate between the temporary table and the permanent table. In the worst case, you may issue a DROP TABLE statement to remove the permanent table instead of the temporary table, which is not expected. Create MySQL temporary table Like the CREATE TABLE statement, MySQL provides many options to create a temporary table. To create a temporary table, you just add the TEMPORARY keyword to the CREATE TABLE statement. For example, the following statement creates a top 10 customers by revenue temporary table based on

the result set of a SELECT statement: 1 CREATE TEMPORARY TABLE top10customers 2 SELECT p.customerNumber, 3 c.customerName, 4 FORMAT(SUM(p.amount),2) total 5 FROM payments p 6 INNER JOIN customers c ON c.customerNumber = p.customerNumber 7 GROUP BY p.customerNumber 8 ORDER BY total DESC 9 LIMIT 10

Drop MySQL temporary table You can use the DROP TABLE statement to remove temporary tables however it is good practice to use the DROP TEMPORARY TABLE statement instead. Because the DROP TEMPORARY TABLE removes only temporary tables, not the permanent tables. In addition, the DROP TEMPORARY TABLE statement helps you avoid the mistake of removing a permanent table when you name your temporary table the same as the name of the permanent table. DROP TEMPORARY TABLE top10customers

SHOW {BINARY | MASTER} LOGS SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count] SHOW CHARACTER SET [like_or_where] SHOW COLLATION [like_or_where] SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [like_or_where] SHOW CREATE DATABASE db_name SHOW CREATE FUNCTION func_name SHOW CREATE PROCEDURE proc_name SHOW CREATE TABLE tbl_name SHOW DATABASES [like_or_where] SHOW ENGINE engine_name {LOGS | STATUS } SHOW [STORAGE] ENGINES SHOW ERRORS [LIMIT [offset,] row_count] SHOW FUNCTION CODE func_name SHOW FUNCTION STATUS [like_or_where] SHOW GRANTS FOR user SHOW INDEX FROM tbl_name [FROM db_name]

SHOW INNODB STATUS SHOW PROCEDURE CODE proc_name SHOW PROCEDURE STATUS [like_or_where] SHOW [BDB] LOGS SHOW MASTER STATUS SHOW MUTEX STATUS SHOW OPEN TABLES [FROM db_name] [like_or_where] SHOW PRIVILEGES SHOW [FULL] PROCESSLIST SHOW SLAVE HOSTS SHOW SLAVE STATUS SHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n] SHOW PROFILES SHOW [GLOBAL | SESSION] STATUS [like_or_where] SHOW TABLE STATUS [FROM db_name] [like_or_where] SHOW [FULL] TABLES [FROM db_name] [like_or_where] SHOW TRIGGERS [FROM db_name] [like_or_where] SHOW [GLOBAL | SESSION] VARIABLES [like_or_where] SHOW WARNINGS [LIMIT [offset,] row_count]

Difference between TRUNCATE, DELETE and DROP commands DELETE The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. SQL> SELECT COUNT(*) FROM emp; COUNT(*) ---------14 SQL> DELETE FROM emp WHERE job = 'CLERK'; 4 rows deleted. SQL> COMMIT; Commit complete. SQL> SELECT COUNT(*) FROM emp; COUNT(*) ---------10

TRUNCATE TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE. SQL> TRUNCATE TABLE emp; Table truncated. SQL> SELECT COUNT(*) FROM emp; COUNT(*) ---------0 DROP The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back. SQL> DROP TABLE emp; Table dropped. SQL> SELECT * FROM emp; SELECT * FROM emp * ERROR at line 1: ORA-00942: table or view does not exist DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back. From Oracle 10g a table can be "undropped". Example: SQL> FLASHBACK TABLE EMP TO BEFORE DROP; Flashback complete. PS: DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. As such, DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back. MySQL/Language/Definitions: what are DDL, DML and DQL?

DDL (Data Definition Language) refers to the CREATE, ALTER and DROP statements

DDL allows to add / modify / delete the logical structures which contain the data or which allow users to access / mantain the data (databases, tables, keys, views...). DDL is about "metadata".

DML (Data Manipulation Language) refers to the INSERT, UPDATE and DELETE statements

DML allows to add / modify / delete data itself.

DQL (Data Query Language) refers to the SELECT, SHOW and HELP statements (queries)

SELECT is the main DQL instruction. It retrieves data you need. SHOW retrieves infos about the metadata. HELP... is for people who need help.

DCL (Data Control Language) refers to the GRANT and REVOKE statements

DCL is used to grant / revoke permissions on databases and their contents. DCL is simple, but MySQL's permissions are rather complex. DCL is about security.

DTL (Data Transaction Language) refers to the START TRANSACTION, SAVEPOINT, COMMIT and ROLLBACK [TO SAVEPOINT] statements

DTL is used to manage transactions (operations which include more instructions none of which can be executed if one of them fails).

Granting Privileges on ----------------------------------------------mysql> or GRANT ALL PRIVILEGES ON

the DatabaseName.*

new TO

database: Username@localhost

mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO Username@localhost IDENTIFIED BY 'newpassword'; mysql> GRANT SELECT,INSERT,UPDATE,DELETE ON vworks.* TO newuser@localhost IDENTIFIED BY 'newpassword'; mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO Username@192.168.0.2 IDENTIFIED BY 'newpassword'; Now a user on the machine '192.168.0.2' can connect to the database. To allow a user to connect from anywhere you would use a wildcard '%' mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO Username@localhost IDENTIFIED BY 'newpassword' WITH GRANT OPTION; This would allow the user 'newuser' to log into the database and give their friend privileges to SELECT,INSERT,UPDATE or DELETE from the database. For example to REVOKE ALL the privileges ON assigned to a user FROM called 'user1':

mysql>

REVOKE

PRIVILEGES

DATABASENAME.*

user1@localhost;

Or just to remove UPDATE, INSERT and DELETE privileges to that data cannot be changed. mysql> REVOKE INSERT,UPDATE,DELETE ON DATABASENAME.* FROM user1@localhost; Backing ------------------------mysqlhotcopy -u <username> Up -p <database> DataBase: /backup/location/

Which SHOULD copy all the tables (*.frm, *.MYI, *.MYD) into the new directory - the script does require the DBI perl module though. To restore these backup files simply copy them back into your MySQL data directory. This is my preferred method of backing up. This outputs the table structure and data in series of SQL commands stored in a text file. The simplified syntax is mysqldump eg: mysqldump Restoring -u a user1 -p DataBase accounts from > dump.sql Dump: -u <username> -p <database> > file.sql

--------------------------------------mysqldump eg: mysqldump -u user1 -p accounts < dump.sql -u <username> -p <database> < file.sql

FLUSH PRIVILEGES; When you create accounts with INSERT, it is necessary to use FLUSH PRIVILEGES to tell the server to reload the grant tables. Otherwise, the changes go unnoticed until you restart the server. With CREATE USER, FLUSH PRIVILEGES is unnecessary.

Queries SELECT customerNumber id, contactLastname name FROM customers UNION SELECT employeeNumber id,firstname name FROM employees SELECT customerNumber id, contactLastname name FROM customers UNION all SELECT employeeNumber id, firstname name FROM employees UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.

Inner join: The MySQL INNER JOIN clause matches rows in one table with rows in other tables SELECT column_list FROM t1 INNER JOIN t2 ON join_condition1 INNER JOIN t3 ON join_condition2 ... WHERE where_conditions;

inner join

left join

The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2). The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

SQL FULL OUTER JOIN Syntax SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name; SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;

MySQL HAVING clause SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000

UPDATE T1, T2 SET T1.c2 = T2.c2, T2.c3 = expr WHERE T1.c1 = T2.c1 AND condition UPDATE T1,T2 INNER JOIN T2 ON T1.C1 = T2.C1 SET T1.C2 = T2.C2, T2.C3 = expr WHERE condition UPDATE employees INNER JOIN merits ON employees.performance = merits.performance SET salary = salary + salary * percentage

UPDATE employees LEFT JOIN merits ON employees.performance = merits.performance SET salary = salary + salary * 0.015; WHERE merits.percentage IS NULL

Delete DELETE FROM employees WHERE officeCode = 4 DELETE FROM employees

DELETE employees, offices FROM employees, offices WHERE employees.officeCode = offices.officeCode AND offices.officeCode = 1

DELETE FROM employees, offices USING employees, offices WHERE employees.officeCode = offices.officeCode AND offices.officeCode = 1

Truncatetruncate table categories

Replace REPLACE INTO categories(categoryname,categoryid)VALUES('PQR','4');

RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. What is SQL?

SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard

SELECT DISTINCT City FROM Customers; SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; SELECT * FROM Customers WHERE City='Berlin' OR City='Mnchen'; SELECT * FROM city='Mnchen'); Customers WHERE Country='Germany' AND (City='Berlin' OR

SELECT * FROM Persons LIMIT 5; SELECT * FROM Persons WHERE ROWNUM <=5; SELECT TOP 2 * FROM Customers; (The following SQL statement selects the two first records from the "Customers" table :) SELECT TOP 50 PERCENT * FROM Customers ;( The following SQL statement selects the first 50% of the records from the "Customers" table) SQL Wildcard Characters

SELECT * FROM Customers WHERE City LIKE 'ber%' ; SELECT * FROM Customers WHERE City LIKE '_erlin'; (The following SQL statement selects all customers with a City starting with any character, followed by "erlin") SELECT * FROM Customers WHERE City LIKE 'L_n_on'; (The following SQL statement selects all customers with a City starting with "L", followed by any character, followed by "n", followed by any character, followed by "on") SELECT * FROM Customers WHERE City LIKE '[bsp]%'; (The following SQL statement selects all customers with a City starting with "b", "s", or "p") SELECT * FROM Customers WHERE City LIKE '[a-c]%'; (The following SQL statement selects all customers with a City starting with "a", "b", or "c") SELECT * FROM Customers WHERE City LIKE '[!bsp]%'; (The following SQL statement selects all customers with a City NOT starting with "b", "s", or "p")

SQL UNION Example The following SQL statement selects all the different cities (only distinct values) from the "Customers" and the "Suppliers" tables: SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;

The following SQL statement uses UNION ALL to select all (duplicate values also) cities from the "Customers" and "Suppliers" tables: SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City;

The following SQL statement uses UNION ALL to select all (duplicate values also) German cities from the "Customers" and "Suppliers" tables: SELECT City, Country FROM Customers WHERE Country='Germany' UNION ALL SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY City;

SQL SELECT INTO Examples Create a backup copy of Customers: SELECT * INTO CustomersBackup2013 FROM Customers; Use the IN clause to copy the table into another database:

SELECT * INTO CustomersBackup2013 IN 'Backup.mdb' FROM Customers; Copy only a few columns into the new table: SELECT CustomerName, ContactName INTO CustomersBackup2013 FROM Customers;

Copy only the German customers into the new table: SELECT * INTO CustomersBackup2013 FROM Customers WHERE Country='Germany'; Copy data from more than one table into the new table: SELECT Customers.CustomerName, Orders.OrderID INTO CustomersOrderBackup2013 FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID; Tip: The SELECT INTO statement can also be used to create a new, empty table using the schema of another. Just add a WHERE clause that causes the query to return no data: SELECT * INTO newtable FROM table1 WHERE 1=0;

SQL INSERT INTO SELECT Examples INSERT INTO Customers (CustomerName, Country)SELECT SupplierName, Country FROM Suppliers WHERE Country='Germany';

NULL Function MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function. In MySQL we can use the IFNULL() function, like this: SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0)) FROM Products or we can use the COALESCE() function, like this: SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0)) FROM Products

Você também pode gostar