Polecenia SQL-a


W Bazie Danych MySQL jest wiele poleceń w języku SQL i kilka nowych. Treść niektórych poleceń SQL jest przytoczona poniżej:
  1. Aktualizuj bazę - przykład:
    mysql> CREATE TABLE t1 (
        ->    a INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        ->    message CHAR(20)) ENGINE=MyISAM;
    mysql> CREATE TABLE t2 (
        ->    a INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        ->    message CHAR(20)) ENGINE=MyISAM;
    mysql> INSERT INTO t1 (message) VALUES ('Testing'),('table'),('t1');
    mysql> INSERT INTO t2 (message) VALUES ('Testing'),('table'),('t2');
    mysql> CREATE TABLE total (
        ->    a INT NOT NULL AUTO_INCREMENT,
        ->    message CHAR(20), INDEX(a))
        ->    ENGINE=MERGE UNION=(t1,t2) INSERT_METHOD=LAST;
  2. Czyść...:
    RESET reset_option [, reset_option] ...
    
    RESET MASTER
    
    RESET SLAVE
  3. Dodaj dane z pliku:
    LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
        [REPLACE | IGNORE]
        INTO TABLE tbl_name
        [FIELDS
            [TERMINATED BY 'string']
            [[OPTIONALLY] ENCLOSED BY 'char']
            [ESCAPED BY 'char']
        ]
        [LINES
            [STARTING BY 'string']
            [TERMINATED BY 'string']
        ]
        [IGNORE number LINES]
        [(col_name_or_user_var,...)]
        [SET col_name = expr,...)]
    
    LOAD DATA FROM MASTER
    
  4. Dodaj wiersz do tabeli:
    INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        VALUES ({expr | DEFAULT},...),(...),...
        [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
    
    Or:
    
    INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
        [INTO] tbl_name
        SET col_name={expr | DEFAULT}, ...
        [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
    
    Or:
    
    INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
        [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
  5. Konwertuj zawartość zmiennej na instrukcję SQL
    PREPARE stmt_name FROM preparable_stmt
  6. Łącz tabele:
    table_references:
        table_reference [, table_reference] ...
    
    table_reference:
        table_factor
      | join_table
    
    table_factor:
        tbl_name [[AS] alias]
            [{USE|IGNORE|FORCE} INDEX (key_list)]
      | ( table_references )
      | { OJ table_reference LEFT OUTER JOIN table_reference
            ON conditional_expr }
    
    join_table:
        table_reference [INNER | CROSS] JOIN table_factor [join_condition]
      | table_reference STRAIGHT_JOIN table_factor
      | table_reference STRAIGHT_JOIN table_factor ON condition
      | table_reference LEFT [OUTER] JOIN table_reference join_condition
      | table_reference NATURAL [LEFT [OUTER]] JOIN table_factor
      | table_reference RIGHT [OUTER] JOIN table_reference join_condition
      | table_reference NATURAL [RIGHT [OUTER]] JOIN table_factor
    
    join_condition:
        ON conditional_expr
      | USING (column_list)
  7. Łącz wiele zapytań w jedno:
    SELECT ...
    UNION [ALL | DISTINCT] SELECT ...
    [UNION [ALL | DISTINCT] SELECT ...]
  8. Modyfikuj istniejące dane:
    UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
        SET col_name1=expr1 [, col_name2=expr2 ...]
        [WHERE where_condition]
        [ORDER BY ...]
        [LIMIT row_count]
    
    Multiple-table syntax:
    
    UPDATE [LOW_PRIORITY] [IGNORE] table_references
        SET col_name1=expr1 [, col_name2=expr2 ...]
        [WHERE where_condition]
  9. Nadaj prawa dostępu do serwera:
    GRANT priv_type [(column_list)] [, priv_type [(column_list)]] ...
        ON [object_type] {tbl_name | * | *.* | db_name.*}
        TO user [IDENTIFIED BY [PASSWORD] 'password']
            [, user [IDENTIFIED BY [PASSWORD] 'password']] ...
        [REQUIRE
            NONE |
            [{SSL| X509}]
            [CIPHER 'cipher' [AND]]
            [ISSUER 'issuer' [AND]]
            [SUBJECT 'subject']]
        [WITH with_option [with_option] ...]
    
    object_type =
        TABLE
      | FUNCTION
      | PROCEDURE
    
    with_option =
        GRANT OPTION
      | MAX_QUERIES_PER_HOUR count
      | MAX_UPDATES_PER_HOUR count
      | MAX_CONNECTIONS_PER_HOUR count
      | MAX_USER_CONNECTIONS count
  10. Odbierz prawa dostępu nadanego poleceniem GRANT:
    REVOKE priv_type [(column_list)] [, priv_type [(column_list)]] ...
        ON [object_type] {tbl_name | * | *.* | db_name.*}
        FROM user [, user] ...
    
    REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ...
  11. Optymalizuj polecenia SQL:
    EXPLAIN [EXTENDED] SELECT select_options
  12. Pokaż...:
    SHOW has many forms that provide information about databases, tables,
    columns, or status information about the server. This section describes
    those following:
    
    SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [LIKE 'pattern']
    SHOW CREATE DATABASE db_name
    SHOW CREATE FUNCTION funcname
    SHOW CREATE PROCEDURE procname
    SHOW CREATE TABLE tbl_name
    SHOW DATABASES [LIKE 'pattern']
    SHOW ENGINE engine_name {LOGS | STATUS }
    SHOW [STORAGE] ENGINES
    SHOW ERRORS [LIMIT [offset,] row_count]
    SHOW FUNCTION STATUS [LIKE 'pattern']
    SHOW GRANTS FOR user
    SHOW INDEX FROM tbl_name [FROM db_name]
    SHOW INNODB STATUS
    SHOW PROCEDURE STATUS [LIKE 'pattern']
    SHOW [BDB] LOGS
    SHOW PRIVILEGES
    SHOW [FULL] PROCESSLIST
    SHOW [GLOBAL | SESSION] STATUS [LIKE 'pattern']
    SHOW TABLE STATUS [FROM db_name] [LIKE 'pattern']
    SHOW [OPEN] TABLES [FROM db_name] [LIKE 'pattern']
    SHOW TRIGGERS
    SHOW [GLOBAL | SESSION] VARIABLES [LIKE 'pattern']
    SHOW WARNINGS [LIMIT [offset,] row_count]
    
    SHOW BINARY LOGS
    SHOW BINLOG EVENTS
    SHOW MASTER STATUS
    SHOW SLAVE HOSTS
    SHOW SLAVE STATUS
  13. Pokaż strukturę:
    {DESCRIBE | DESC} tbl_name [col_name | wild]
  14. Pokaż zmiany:
    ALTER
        [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
        [DEFINER = { user | CURRENT_USER }]
        [SQL SECURITY { DEFINER | INVOKER }]
        VIEW view_name [(column_list)]
        AS select_statement
        [WITH [CASCADED | LOCAL] CHECK OPTION]
  15. Przeładuj...:
    FLUSH [LOCAL | NO_WRITE_TO_BINLOG] flush_option [, flush_option] ...
  16. Serwer SLAVE (start, stop) - replikacje:
    START SLAVE [thread_type [, thread_type] ... ]
    START SLAVE [SQL_THREAD] UNTIL
        MASTER_LOG_FILE = 'log_name', MASTER_LOG_POS = log_pos
    START SLAVE [SQL_THREAD] UNTIL
        RELAY_LOG_FILE = 'log_name', RELAY_LOG_POS = log_pos
    
    thread_type: IO_THREAD | SQL_THREAD
    
    STOP SLAVE [thread_type [, thread_type] ... ]
    
    thread_type: IO_THREAD | SQL_THREAD
  17. Ustaw...:
    SET variable_assignment [, variable_assignment] ...
    
    variable_assignment:
          user_var_name = expr
        | [GLOBAL | SESSION] system_var_name = expr
        | [@@global. | @@session. | @@]system_var_name = expr
    
    SET GLOBAL SQL_SLAVE_SKIP_COUNTER = N
    SET SQL_LOG_BIN = {0|1}
  18. Ustaw więzy:
    [CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
        REFERENCES tbl_name (index_col_name, ...)
        [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
        [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
    Example
    CREATE TABLE product (category INT NOT NULL, id INT NOT NULL,
                          price DECIMAL,
                          PRIMARY KEY(category, id)) ENGINE=INNODB;
    CREATE TABLE customer (id INT NOT NULL,
                           PRIMARY KEY (id)) ENGINE=INNODB;
    CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT,
                                product_category INT NOT NULL,
                                product_id INT NOT NULL,
                                customer_id INT NOT NULL,
                                PRIMARY KEY(no),
                                INDEX (product_category, product_id),
                                FOREIGN KEY (product_category, product_id)
                                  REFERENCES product(category, id)
                                  ON UPDATE CASCADE ON DELETE RESTRICT,
                                INDEX (customer_id),
                                FOREIGN KEY (customer_id)
                                  REFERENCES customer(id)) ENGINE=INNODB;
  19. Ustaw hasło:
    SET PASSWORD [FOR user] = PASSWORD('some password')
    SET PASSWORD FOR 'bob'@'%.loc.gov' = PASSWORD('newpass');
  20. Usuń bazę:
    DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
  21. Usuń funkcję:
    DROP FUNCTION function_name
  22. Usuń index:
    DROP INDEX index_name ON tbl_name
  23. Usuń rekordy z tabeli:
    DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
        [WHERE where_condition]
        [ORDER BY ...]
        [LIMIT row_count]
    
    Multiple-table syntax:
    
    DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
        tbl_name[.*] [, tbl_name[.*]] ...
        FROM table_references
        [WHERE where_condition]
    
    Or:
    
    DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
        FROM tbl_name[.*] [, tbl_name[.*]] ...
        USING table_references
        [WHERE where_condition]
  24. Usuń tabelę:
    DROP [TEMPORARY] TABLE [IF EXISTS]
        tbl_name [, tbl_name] ...
        [RESTRICT | CASCADE]
  25. Usuń użytkownika:
    DROP USER user [, user] ...
  26. Usuń widok:
    DROP VIEW [IF EXISTS]
        view_name [, view_name] ...
        [RESTRICT | CASCADE]
  27. Usuń wszystkie rekordy z tabeli:
    TRUNCATE [TABLE] tbl_name
  28. Usuń zapytanie uruchomione w tle;
    DROP TRIGGER [schema_name.]trigger_name
  29. Utwórz bazę:
    CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
        [create_specification [, create_specification] ...]
    
    create_specification:
        [DEFAULT] CHARACTER SET charset_name
      | [DEFAULT] COLLATE collation_name
  30. Utwórz funkcję:
    CREATE [AGGREGATE] FUNCTION function_name RETURNS {STRING|INTEGER|REAL|DECIMAL}
        SONAME shared_library_name
  31. Utwórz index:
    CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
        [index_type]
        ON tbl_name (index_col_name,...)
    
    index_col_name:
        col_name [(length)] [ASC | DESC]
    
    index_type:
        USING {BTREE | HASH}
  32. Utwórz tabelę:
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
        (create_definition,...)
        [table_option ...]
    
    Or:
    
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
        [(create_definition,...)]
        [table_option ...]
        select_statement
    
    Or:
    
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
        { LIKE old_tbl_name | (LIKE old_tbl_name) }
    
    create_definition:
        column_definition
      | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...)
      | {INDEX|KEY} [index_name] [index_type] (index_col_name,...)
      | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY]
          [index_name] [index_type] (index_col_name,...)
      | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (index_col_name,...)
      | [CONSTRAINT [symbol]] FOREIGN KEY
          [index_name] (index_col_name,...) [reference_definition]
      | CHECK (expr)
    
    column_definition:
        col_name data_type [NOT NULL | NULL] [DEFAULT default_value]
          [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
          [COMMENT 'string'] [reference_definition]
    
    data_type:
        BIT[(length)]
      | TINYINT[(length)] [UNSIGNED] [ZEROFILL]
      | SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
      | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
      | INT[(length)] [UNSIGNED] [ZEROFILL]
      | INTEGER[(length)] [UNSIGNED] [ZEROFILL]
      | BIGINT[(length)] [UNSIGNED] [ZEROFILL]
      | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
      | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
      | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
      | DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
      | NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
      | DATE
      | TIME
      | TIMESTAMP
      | DATETIME
      | YEAR
      | CHAR(length)
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | VARCHAR(length)
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | BINARY(length)
      | VARBINARY(length)
      | TINYBLOB
      | BLOB
      | MEDIUMBLOB
      | LONGBLOB
      | TINYTEXT [BINARY]
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | TEXT [BINARY]
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | MEDIUMTEXT [BINARY]
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | LONGTEXT [BINARY]
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | ENUM(value1,value2,value3,...)
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | SET(value1,value2,value3,...)
          [CHARACTER SET charset_name] [COLLATE collation_name]
      | spatial_type
    
    index_col_name:
        col_name [(length)] [ASC | DESC]
    
    index_type:
        USING {BTREE | HASH}
    
    reference_definition:
        REFERENCES tbl_name [(index_col_name,...)]
          [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
          [ON DELETE reference_option]
          [ON UPDATE reference_option]
    
    reference_option:
        RESTRICT | CASCADE | SET NULL | NO ACTION
    
    table_option:
        {ENGINE|TYPE} [=] engine_name
      | AUTO_INCREMENT [=] value
      | AVG_ROW_LENGTH [=] value
      | [DEFAULT] CHARACTER SET charset_name
      | CHECKSUM [=] {0 | 1}
      | COLLATE collation_name
      | COMMENT [=] 'string'
      | CONNECTION [=] 'connect_string'
      | DATA DIRECTORY [=] 'absolute path to directory'
      | DELAY_KEY_WRITE [=] {0 | 1}
      | INDEX DIRECTORY [=] 'absolute path to directory'
      | INSERT_METHOD [=] { NO | FIRST | LAST }
      | MAX_ROWS [=] value
      | MIN_ROWS [=] value
      | PACK_KEYS [=] {0 | 1 | DEFAULT}
      | PASSWORD [=] 'string'
      | ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT}
      | UNION [=] (tbl_name[,tbl_name]...)
    
    select_statement:
        [IGNORE | REPLACE] [AS] SELECT ...   (Some legal select statement)
  33. Utwórz użytkownika:
    CREATE USER user [IDENTIFIED BY [PASSWORD] 'password']
        [, user [IDENTIFIED BY [PASSWORD] 'password']] ...
  34. Utwórz zapytanie uruchamiane w tle:
    CREATE
        [DEFINER = { user | CURRENT_USER }]
        TRIGGER trigger_name trigger_time trigger_event
        ON tbl_name FOR EACH ROW trigger_stmt
  35. Wprowadź zmiany w bazie:
    ALTER {DATABASE | SCHEMA} [db_name]
        alter_specification [, alter_specification] ...
    
    alter_specification:
        [DEFAULT] CHARACTER SET charset_name
      | [DEFAULT] COLLATE collation_name
  36. Wprowadź zmiany w tabeli:
    ALTER [IGNORE] TABLE tbl_name
        alter_specification [, alter_specification] ...
    
    alter_specification:
        ADD [COLUMN] column_definition [FIRST | AFTER col_name ]
      | ADD [COLUMN] (column_definition,...)
      | ADD {INDEX|KEY} [index_name] [index_type] (index_col_name,...)
      | ADD [CONSTRAINT [symbol]]
            PRIMARY KEY [index_type] (index_col_name,...)
      | ADD [CONSTRAINT [symbol]]
            UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...)
      | ADD [FULLTEXT|SPATIAL] [INDEX|KEY] [index_name] (index_col_name,...)
      | ADD [CONSTRAINT [symbol]]
            FOREIGN KEY [index_name] (index_col_name,...)
            [reference_definition]
      | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
      | CHANGE [COLUMN] old_col_name column_definition
            [FIRST|AFTER col_name]
      | MODIFY [COLUMN] column_definition [FIRST | AFTER col_name]
      | DROP [COLUMN] col_name
      | DROP PRIMARY KEY
      | DROP {INDEX|KEY} index_name
      | DROP FOREIGN KEY fk_symbol
      | DISABLE KEYS
      | ENABLE KEYS
      | RENAME [TO] new_tbl_name
      | ORDER BY col_name
      | CONVERT TO CHARACTER SET charset_name [COLLATE collation_name]
      | [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name]
      | DISCARD TABLESPACE
      | IMPORT TABLESPACE
      | table_option ...
    
    index_col_name:
        col_name [(length)] [ASC | DESC]
    
    index_type:
        USING {BTREE | HASH}
  37. Zakończ połączenie z serwerem:
    KILL [CONNECTION | QUERY] thread_id
  38. Zamień wszystkie znaki w stringu na duże litery
    Upper(string)
  39. Zapytanie pokaż...:
    SELECT
        [ALL | DISTINCT | DISTINCTROW ]
          [HIGH_PRIORITY]
          [STRAIGHT_JOIN]
          [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
          [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
        select_expr, ...
        [FROM table_references
        [WHERE where_condition]
        [GROUP BY {col_name | expr | position}
          [ASC | DESC], ... [WITH ROLLUP]]
        [HAVING where_condition]
        [ORDER BY {col_name | expr | position}
          [ASC | DESC], ...]
        [LIMIT {[offset,] row_count | row_count OFFSET offset}]
        [PROCEDURE procedure_name(argument_list)]
        [INTO OUTFILE 'file_name' export_options
          | INTO DUMPFILE 'file_name'
          | INTO @var_name [, @var_name]]
        [FOR UPDATE | LOCK IN SHARE MODE]]
  40. Zastosuj podaną bazę jako domyślną:
    USE nazwa_bazy
  41. Zmień nazwę tabeli:
    RENAME TABLE tbl_name TO new_tbl_name
        [, tbl_name2 TO new_tbl_name2] ...
  42. Zmień uprawnionego użytkownika:
    RENAME USER old_user TO new_user
        [, old_user TO new_user] ...

do góry