introducción rápida a sql
DESCRIPTION
Curso de introducción a SQL utilizando MySQL y Workbench.TRANSCRIPT
![Page 1: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/1.jpg)
Introducción rápida a SQLUsando MySQL y Workbench
Carlos Hernando [email protected]
5 y 9 de Mayo de 2011
![Page 2: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/2.jpg)
Índice de contenidos
Introducción a las bases de datosIntroducción a MySQLSintaxis de SQL
Uso de MySQL Worbench
![Page 3: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/3.jpg)
Advertencia
Esto no es un curso formal en teoríaEs una introducción rápida y sucia de SQLBasado en el temario del curso: MySQL for Developers
![Page 4: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/4.jpg)
Introducción a las bases de datos
![Page 5: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/5.jpg)
Conceptos
EntidadAtributo, una propiedad de la EntidadRegistro, una fi la que representa la Entidad con sus atributosTabla, una sucesión de registros tabulados por sus atributos de un mismo tipo de Entidad
![Page 6: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/6.jpg)
Conceptos
Base de datos, conjunto de Tablas
Servidor, lugar dónde residen las Bases de DatosBases de datos relacionalesSQL, Structured Query Language
DDL, Data Defi nition LanguageDML, Data Manipulation Language
![Page 7: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/7.jpg)
Introducción a MySQL
![Page 8: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/8.jpg)
Servidor MySQL
Http://www.mysql.com/Comprado por OracleDisponible gratuitamenteMuy extendido
![Page 9: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/9.jpg)
Estructura Cliente / Servidor
El servidor mantiene las bases de datosEl cliente realiza operaciones mediante sentencias SQL.La principal carga de trabajo recae en el servidor.
![Page 10: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/10.jpg)
Instalación de MySQL
ServidorMySQL Community Serverhttp://www.mysql.com/downloads/mysql/
El CCFI ya ha instalado el servidor pero no está activado
![Page 11: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/11.jpg)
MySQL Workbench
Herramienta de gestión, consulta y diseñohttp://wb.mysql.com/Lo utilizaremos como apoyo
![Page 12: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/12.jpg)
![Page 13: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/13.jpg)
Sintaxis SQL
![Page 14: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/14.jpg)
Tipos de sentencias
De consulta:SHOWDESCSELECT
De manipulación:CREATEINSERTUPDATEALTER
![Page 15: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/15.jpg)
Obtener información de una tabla
SHOW TABLESDESC tabla
http://dev.mysql.com/doc/refman/5.1/en/describe.html
![Page 16: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/16.jpg)
QuerySELECT [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 [, 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'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
http://dev.mysql.com/doc/refman/5.1/en/select.html
![Page 17: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/17.jpg)
Condicionales
expr OR expr | expr || expr | expr XOR expr | expr AND expr | expr && expr | NOT expr | ! expr | boolean_primary IS [NOT] {TRUE | FALSE | UNKNOWN} | boolean_primary
comparison_operator: = | >= | > | <= | < | <> | !=
predicate: bit_expr [NOT] IN (subquery) | bit_expr [NOT] IN (expr [, expr] ...) | bit_expr [NOT] BETWEEN bit_expr AND predicate | bit_expr SOUNDS LIKE bit_expr | bit_expr [NOT] LIKE simple_expr [ESCAPE simple_expr] | bit_expr [NOT] REGEXP bit_expr | bit_expr
http://dev.mysql.com/doc/refman/5.1/en/expressions.html
![Page 18: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/18.jpg)
Funciones
AVG()CONCAT()COUNT()CURRENT_DATE()IF()TRIM()LOWER()
http://dev.mysql.com/doc/refman/5.1/en/func-op-summary-ref.html
![Page 19: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/19.jpg)
Union
Agregación de tablasMismas columnas
SELECT ...UNION [ALL | DISTINCT] SELECT ...[UNION [ALL | DISTINCT] SELECT ...]
![Page 20: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/20.jpg)
Creación de una base de datos
CREATE DATABASE curso;
![Page 21: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/21.jpg)
Fijar la base de datos
Un servidor puede alojar múltiples bases de datosLas operaciones SQL pueden referirse a cualquiera de estas tablasPara utilizar una base de datos en concreto utilizamosUSE pruebas;
![Page 22: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/22.jpg)
Destruir una base de datos
DROP DATABASE pruebas;
![Page 23: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/23.jpg)
Cargar y guardar volcados
Base de datos � FicheroMySQLdump
Fichero � Base de datosEjecutar sentencias SQL
![Page 24: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/24.jpg)
Creación de una tabla
CREATE TABLE `jugador` ( `id` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1
![Page 25: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/25.jpg)
Propiedades de una tabla
Tipo de ENGINEMyISAMInnoDB
CharsetLatin1UTF8
![Page 26: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/26.jpg)
Tipos de datos
NuméricosCadenasBinariosTiempo
![Page 27: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/27.jpg)
Numéricos
EnterosTINYINTINTBIGINT
Coma fl otanteFLOAT
Coma fi jaDECIMAL
http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html
![Page 28: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/28.jpg)
Cadenas
CHARVARCHARBLOBENUMSET
http://dev.mysql.com/doc/refman/5.1/en/string-types.html
![Page 29: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/29.jpg)
Binarios
BINARYVARBINARY
http://dev.mysql.com/doc/refman/5.1/en/binary-varbinary.html
![Page 30: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/30.jpg)
Tiempo
DATETIMEDATETIMETIMESTAMPYEAR
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-types.html
![Page 31: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/31.jpg)
Tipos de datos (de nuevo) 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
![Page 32: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/32.jpg)
NULL y valores de fábrica
NULL | NOT NULLDEFAULT 'valor'
![Page 33: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/33.jpg)
Alterar una tabla
ALTER TABLE jugador ADD COLUMN universo VARCHAR(20) NOT NULL AFTER nombre;
ALTER TABLE jugador DROP COLUMN universo;
ALTER TABLE jugador ADD KEY universo;
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
![Page 34: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/34.jpg)
Eliminar una tabla
DROP TABLE jugador;
![Page 35: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/35.jpg)
Foreign Keys
En tiempo de creación: REFERENCES tbl_name (index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option]
http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
![Page 36: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/36.jpg)
Foreign Keys
Una vez creada la tabla:ALTER TABLE jugador ADD FOREIGN KEY index_name (index_col_name) reference_defi nition
![Page 37: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/37.jpg)
CASCADE
ON UPDATEON DELETE
![Page 38: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/38.jpg)
INSERT
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] ... ]
![Page 39: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/39.jpg)
DELETE
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
![Page 40: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/40.jpg)
UPDATE
UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
![Page 41: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/41.jpg)
REPLACE
REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
![Page 42: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/42.jpg)
INSERT ON DUPLICATE KEY
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
![Page 43: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/43.jpg)
TRUNCATE
TRUNCATE [TABLE] tbl_name
![Page 44: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/44.jpg)
Transacciones
START TRANSACTION [WITH CONSISTENT SNAPSHOT] | BEGIN [WORK]COMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]ROLLBACK [WORK] [AND [NO] CHAIN] [[NO] RELEASE]SET autocommit = {0 | 1}
![Page 45: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/45.jpg)
LOCK
LOCK TABLES tbl_name [[AS] alias] lock_type [, tbl_name [[AS] alias] lock_type] ...
lock_type: READ [LOCAL] | [LOW_PRIORITY] WRITE
UNLOCK TABLES
![Page 46: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/46.jpg)
Consultas a múltiples tablas
JOINSubquery
![Page 47: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/47.jpg)
JOIN
SELECT t1.name, t2.salary FROM employee t1 INNER JOIN info t2 ON t1.name = t2.name
SELECT t1.name, t2.salay FROM employee t1, info t2 WHERE t1.name = t2.name
![Page 48: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/48.jpg)
Tipos de JOIN
table_reference [INNER | CROSS] JOIN table_factor [join_condition] | table_reference STRAIGHT_JOIN table_factor | table_reference STRAIGHT_JOIN table_factor ON conditional_expr | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_condition | table_reference NATURAL [{LEFT|RIGHT} [OUTER]] JOIN table_factor
![Page 49: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/49.jpg)
Subqueries
SELECT * FROM t1 WHERE column1 =(SELECT column1 FROM t2);
![Page 50: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/50.jpg)
Vistas
CREATE [OR REPLACE] [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]
![Page 51: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/51.jpg)
Procedimientos
CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic ...] routine_body
![Page 52: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/52.jpg)
Triggers
CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body
![Page 53: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/53.jpg)
Caso práctico
![Page 54: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/54.jpg)
Ejercicio
Crear las tablas del siguiente diagramaCrear las vistas asociadas (SELECT)Insertar una Notifi cación al insertar una nueva tarea (TRIGGER)Crear un procedimiento “tarea_notifi cada” (STORED PROCEDURE) que elimine la notifi cación y ponga la tarea en el estado “progreso”
![Page 55: Introducción rápida a SQL](https://reader033.vdocuments.site/reader033/viewer/2022051209/54922af4b479598e6a8b560d/html5/thumbnails/55.jpg)
Diseño orientativo