Thứ Năm, 16 tháng 11, 2017

MySQL Cheat Sheet

MySQL Command-Line
WhatHowExample(s)
Running MySQLmysql -uusername -ppasswordmysql -ucusack2RO -pegbdf5s
Importingmysql -uusername -ppassword < filenamemysql -usomeDB -pblah < myNewDB.sql
Dumping
(Saving)
mysqldump -uusername -ppassword database [tables] > filename mysqldump -ume -pblah myDB > My.sql
mysqldump -ume -pblah myDB table1
        table2 > my.sql

Common MySQL Column Types
PurposeData TypeExample
Integersint(M)int(5)
Floating-point (real) numbersfloat(M,D)float(12,3)
Double-precision floating-pointdouble(M,D)double(20,3)
Dates and timestimestamp(M)timestamp(8) (for YYYYMMDD)
timestamp(12) (for YYYYMMDDHHMMSS)
Fixed-length stringschar(M)char(10)
Variable-length stringsvarchar(M)varchar(20)
A large amount of textblobblob
Values chosen from a listenum('value1',value2',...)enum('apples','oranges','bananas')

M is maximum to display, and D is precision to the right of the decimal.
MySQL Mathematical Functions
WhatHow
Count rows per groupCOUNT(column | *)
Average value of groupAVG(column)
Minumum value of groupMIN(column)
Maximum value of groupMAX(column)
Sum values in a groupSUM(column)
Absolute valueabs(number)
Rounding numbersround(number)
Largest integer not greaterfloor(number)
Smallest integer not smallerceiling(number)
Square rootsqrt(number)
nth powerpow(base,exponent)
random number n, 0<n < 1rand()
sin (similar cos, etc.)sin(number)
MySQL String Functions
WhatHow
Compare stringsstrcmp(string1,string2)
Convert to lower caselower(string)
Convert to upper caseupper(string)
Left-trim whitespace (similar right)ltrim(string)
Substring of stringsubstring(string,index1,index2)
Encrypt passwordpassword(string)
Encode stringencode(string,key)
Decode stringdecode(string,key)
Get datecurdate()
Get timecurtime()
Extract day name from date stringdayname(string)
Extract day number from date stringdayofweek(string)
Extract month from date stringmonthname(string)
Basic MySQL Commands
WhatHowExample(s)
List all databasesSHOW DATABASES;SHOW DATABASES;
Create databaseCREATE DATABASE database;CREATE DATABASE PhoneDB;
Use a databaseUSE database;USE PhonDB;
List tables in the databaseSHOW TABLES;SHOW TABLES;
Show the structure of a tableDESCRIBE table;
SHOW COLUMNS FROM table;
DESCRIBE Animals;
SHOW COLUMNS FROM Animals;
Delete a database (Careful!)DROP DATABASE database;DROP DATABASE PhoneDB;
SQL Commands: Modifying
WhatHowExample(s)
Create tableCREATE TABLE table (
        column1 type [[NOT] NULL]
                [AUTO_INCREMENT],
        column2 type [[NOT] NULL]
                [AUTO_INCREMENT],
        ...
        other options,
        PRIMARY KEY (column(s))    );
CREATE TABLE Students (
        LastName varchar(30) NOT NULL,
        FirstName varchar(30) NOT NULL,
        StudentID int NOT NULL,
        Major varchar(20),
        Dorm varchar(20),
        PRIMARY KEY (StudentID)     );
Insert dataINSERT INTO table VALUES
        (list of values);
INSERT INTO table SET
        column1=value1,
        column2=value2,
        ...
        columnk=valuek;
INSERT INTO table (column1,column2,...)
        VALUES (value1,value2...);
INSERT INTO Students VALUES
        ('Smith','John',123456789,'Math','Selleck');
INSERT INTO Students SET
        FirstName='John',
        LastName='Smith',
        StudentID=123456789,
        Major='Math';
INSERT INTO Students
        (StudentID,FirstName,LastName)
        VALUES (123456789,'John','Smith');
Insert/SelectINSERT INTO table (column1,column2,...)
        SELECT statement;
        (See below)
INSERT INTO Students
        (StudentID,FirstName,LastName)
        SELECT StudentID,FirstName,LastName
        FROM OtherStudentTable;
        WHERE LastName like '%son';
Delete dataDELETE FROM table
        [WHERE condition(s)];



(Omit WHERE to delete all data)
DELETE FROM Students
        WHERE LastName='Smith';
DELETE FROM Students
        WHERE LastName like '%Smith%';
        AND FirstName='John';
DELETE FROM Students;
Updating DataUPDATE table SET
        column1=value1,
        column2=value2,
        ...
        columnk=valuek
        [WHERE condition(s)];
UPDATE Students SET
        LastName='Jones' WHERE
        StudentID=987654321;
UPDATE Students SET
        LastName='Jones', Major='Theatre'
        WHERE StudentID=987654321 OR
        (MAJOR='Art' AND FirstName='Pete');
Insert columnALTER TABLE table ADD COLUMN
        column type options;
ALTER TABLE Students ADD COLUMN
        Hometown varchar(20);
Delete columnALTER TABLE table
        DROP COLUMN column;
ALTER TABLE Students
        DROP COLUMN Dorm;
Delete table (Careful!)DROP TABLE [IF EXISTS] table;DROP TABLE Animals;
SQL Commands: Querying
WhatHowExample(s)
All columnsSELECT * FROM table;SELECT * FROM Students;
Some columnsSELECT column1,column2,... FROM table;SELECT LastName, FirstName FROM Students;
Some rows/
columns
SELECT column1,column2,...
        FROM table
        [WHERE condition(s)];
SELECT LastName,FirstName
        FROM Students
        WHERE StudentID LIKE '%123%';
No RepeatsSELECT [DISTINCT] column(s)
        FROM table;
SELECT DISTINCT LastName
        FROM Students;
OrderingSELECT column1,column2,...
        FROM table
        [ORDER BY column(s) [DESC]];
SELECT LastName,FirstName
        FROM Students
        ORDER BY LastName, FirstName DESC;
Column
Aliases
SELECT column1 [AS alias1],
        column2 [AS alias2], ...
        FROM table1;
SELECT LastName,FirstName AS First
        FROM Students;
GroupingSELECT column1,column2,...
        FROM table
        [GROUP BY column(s)];
SELECT LastName,COUNT(*)
        FROM Students
        GROUP BY LastName;
Group FilteringSELECT column1,column2,...
        FROM table
        [GROUP BY column(s)]
        [HAVING condition(s)];
SELECT LastName,COUNT(*)
        FROM Students
        GROUP BY LastName
        HAVING LastName like '%son';
JoinsSELECT column1,column2,...
        FROM table1,table2,...
        [WHERE condition(s)];
SELECT LastName,Points
        FROM Students,Assignments
        WHERE AssignmentID=12 AND
        Students.StudentID=Assignments.StudentID;
Table
Aliases
SELECT column1,column2,...
        FROM table1 [alias1],
        table2 [alias2],...
        [WHERE condition(s)];
SELECT LastName,Points
        FROM Students S,Assignments A
        WHERE S.StudentID=A.StudentID AND
        A.AssignmentID=12;
EverythingSELECT [DISTINCT]
        column1 [AS alias1],
        column2 [AS alias2], ...
        FROM table1 [alias1],
        table2 [alias2],...
        [WHERE condition(s)]
        [GROUP BY column(s)]
        [HAVING condition(s)]
        [ORDER BY column(s) [DESC]];
SELECT Points, COUNT(*) AS Cnt
        FROM Students S,Assignments A
        WHERE S.StudentID=A.StudentID AND
        A.AssignmentID=12
        GROUP BY Points
        HAVING Points > 10
        ORDER BY Cnt, Points DES


Create DB:

CREATE DATABASE `database_name` CHARACTER SET utf8 COLLATE utf8_general_ci;

Create new user all privilege

CREATE USER 'user'@'host' IDENTIFIED BY 'PASSWORD';
GRANT ALL PRIVILEGES ON * . * TO 'user'@'host';
FLUSH PRIVILEGES;

Create new user some privilege

CREATE USER 'user'@'host' IDENTIFIED BY 'PASSWORD';
GRANT ALTER,CREATE,DELETE,INSERT,INDEX,SELECT,UPDATE ON * . * TO 'user'@'host';
FLUSH PRIVILEGES;

GRANT PRIVILEGES

GRANT SELECT ON database.* TO user@'localhost';
If you intend to create a brand new user, then run this:

GRANT SELECT ON database.* TO user@'localhost' IDENTIFIED BY 'password';
To enable more options, you would separate them with a comma. So to enable SELECT, INSERT, and DELETE your syntax would look like this:

GRANT SELECT, INSERT, DELETE ON database TO username@'localhost' IDENTIFIED BY 'password';
Once you have given the desired privileges for your user, you will need to run this command within the MySQL command prompt:

FLUSH PRIVILEGES;
To see a list of the privileges that have been granted to a specific user:

select * from mysql.user where User='username';
This is a list of privileges that you can grant:
PrivilegeMeaning
ALL [PRIVILEGES]Sets all simple privileges except GRANT OPTION
ALTEREnables use of ALTER TABLE
CREATEEnables use of CREATE TABLE
CREATE TEMPORARY TABLESEnables use of CREATE TEMPORARY TABLE
DELETEEnables use of DELETE
DROPEnables use of DROP TABLE
EXECUTENot implemented
FILEEnables use of SELECT ... INTO OUTFILE and LOAD DATA INFILE
INDEXEnables use of CREATE INDEX and DROP INDEX
INSERTEnables use of INSERT
LOCK TABLESEnables use of LOCK TABLES on tables for which you have the SELECT privilege
PROCESSEnables the user to see all processes with SHOW PROCESSLIST
REFERENCESNot implemented
RELOADEnables use of FLUSH
REPLICATION CLIENTEnables the user to ask where slave or master servers are
REPLICATION SLAVENeeded for replication slaves (to read binary log events from the master)
SELECTEnables use of SELECT
SHOW DATABASESSHOW DATABASES shows all databases
SHUTDOWNEnables use of MySQLadmin shutdown
SUPEREnables use of CHANGE MASTER, KILL, PURGE MASTER LOGS, and SET GLOBAL statements, the MySQLadmin debug command; allows you to connect (once) even if max_connections is reached
UPDATEEnables use of UPDATE
USAGESynonym for privileges
GRANT OPTIONEnables privileges to be granted

mysql -u your_user your_database <c:\path\to\your_script.sql >stdout_output.txt 2>stderr_output.txt

a

Share This!


Không có nhận xét nào:

Đăng nhận xét