Introducción rápida a SQL
Upcoming SlideShare
Loading in...5
×
 

Introducción rápida a SQL

on

  • 1,636 views

Curso de introducción a SQL utilizando MySQL y Workbench.

Curso de introducción a SQL utilizando MySQL y Workbench.

Statistics

Views

Total Views
1,636
Views on SlideShare
1,634
Embed Views
2

Actions

Likes
0
Downloads
67
Comments
0

2 Embeds 2

https://twitter.com 1
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Introducción rápida a SQL Introducción rápida a SQL Presentation Transcript

  • Introducción rápida a SQL Usando MySQL y Workbench Carlos Hernando Carasol chernando@acm.org 5 y 9 de Mayo de 2011
  • Índice de contenidos Introducción a las bases de datos Introducción a MySQL Sintaxis de SQL Uso de MySQL Worbench
  • Advertencia Esto no es un curso formal en teoría Es una introducción rápida y sucia de SQL Basado en el temario del curso: MySQL for Developers
  • Introducción a las bases de datos
  • Conceptos Entidad Atributo, una propiedad de la Entidad Registro, una f la que representa la i Entidad con sus atributos Tabla, una sucesión de registros tabulados por sus atributos de un mismo tipo de Entidad
  • Conceptos Base de datos, conjunto de Tablas Servidor, lugar dónde residen las Bases de Datos Bases de datos relacionales SQL, Structured Query Language DDL, Data Def nition Language i DML, Data Manipulation Language
  • Introducción a MySQL
  • Servidor MySQL Http://www.mysql.com/ Comprado por Oracle Disponible gratuitamente Muy extendido
  • Estructura Cliente / Servidor El servidor mantiene las bases de datos El cliente realiza operaciones mediante sentencias SQL. La principal carga de trabajo recae en el servidor.
  • Instalación de MySQL Servidor MySQL Community Server http://www.mysql.com/downloads/mysql/ El CCFI ya ha instalado el servidor pero no está activado
  • MySQL Workbench Herramienta de gestión, consulta y diseño http://wb.mysql.com/ Lo utilizaremos como apoyo
  • Sintaxis SQL
  • Tipos de sentencias De consulta: SHOW DESC SELECT De manipulación: CREATE INSERT UPDATE ALTER
  • Obtener información de una tabla SHOW TABLES DESC tabla http://dev.mysql.com/doc/refman/5.1/en/describe.html
  • QuerySELECT [HAVING where_condition] [ALL | DISTINCT | DISTINCTROW ] [ORDER BY {col_name | expr | position} [HIGH_PRIORITY] [ASC | DESC], ...] [STRAIGHT_JOIN] [LIMIT {[offset,] row_count | row_count [SQL_SMALL_RESULT] OFFSET offset}][SQL_BIG_RESULT][SQL_BUFFER_RESULT] [PROCEDURE [SQL_CACHE | SQL_NO_CACHE] procedure_name(argument_list)][SQL_CALC_FOUND_ROWS] [INTO OUTFILE file_name select_expr [, select_expr ...] [CHARACTER SET charset_name] [FROM table_references export_options [WHERE where_condition] | INTO DUMPFILE file_name [GROUP BY {col_name | expr | position} | INTO var_name [, var_name]] [ASC | DESC], ... [WITH ROLLUP]] [FOR UPDATE | LOCK IN SHARE MODE]] http://dev.mysql.com/doc/refman/5.1/en/select.html
  • Condicionales expr OR expr comparison_operator: = | >= | > | <= | < | <> | != | expr || expr predicate: | expr XOR expr bit_expr [NOT] IN (subquery) | expr AND expr | bit_expr [NOT] IN (expr [, expr] ...) | expr && expr | bit_expr [NOT] BETWEEN bit_expr AND predicate | NOT expr | bit_expr SOUNDS LIKE bit_expr | bit_expr [NOT] LIKE simple_expr | ! expr [ESCAPE simple_expr] | boolean_primary IS | bit_expr [NOT] REGEXP bit_expr[NOT] {TRUE | FALSE | | bit_exprUNKNOWN} | boolean_primary http://dev.mysql.com/doc/refman/5.1/en/expressions.html
  • Funciones AVG() CONCAT() COUNT() CURRENT_DATE() IF() TRIM() LOWER() http://dev.mysql.com/doc/refman/5.1/en/func-op-summary-ref.html
  • Union Agregación de SELECT ... tablas UNION [ALL | Mismas columnas DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]
  • Creación de una base de datosCREATE DATABASE curso;
  • Fijar la base de datos Un servidor puede alojar múltiples bases de datos Las operaciones SQL pueden referirse a cualquiera de estas tablas Para utilizar una base de datos en concreto utilizamos USE pruebas;
  • Destruir una base de datosDROP DATABASE pruebas;
  • Cargar y guardar volcados Base de datos Fichero MySQLdump Fichero Base de datos Ejecutar sentencias SQL
  • Creación de una tablaCREATE TABLE `jugador` ( `id` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULTCHARSET=latin1
  • Propiedades de una tabla Tipo de ENGINE MyISAM InnoDB Charset Latin1 UTF8
  • Tipos de datos Numéricos Cadenas Binarios Tiempo
  • Numéricos Enteros TINYINT INT BIGINT Coma f otante l FLOAT Coma f ja i DECIMAL http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html
  • Cadenas CHAR VARCHAR BLOB ENUM SET http://dev.mysql.com/doc/refman/5.1/en/string-types.html
  • Binarios BINARY VARBINARY http://dev.mysql.com/doc/refman/5.1/en/binary-varbinary.html
  • Tiempo DATETIME DATE TIME TIMESTAMP YEAR http://dev.mysql.com/doc/refman/5.1/en/date-and-time-types.html
  • Tipos de datos (de nuevo) BIT[(length)] | CHAR[(length)]| TINYINT[(length)] [UNSIGNED] [ZEROFILL] [CHARACTER SET charset_name] [COLLATE collation_name]| SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | VARCHAR(length)| MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] [CHARACTER SET charset_name] [COLLATE collation_name]| INT[(length)] [UNSIGNED] [ZEROFILL] | BINARY[(length)]| INTEGER[(length)] [UNSIGNED] [ZEROFILL] | VARBINARY(length)| BIGINT[(length)] [UNSIGNED] [ZEROFILL] | TINYBLOB| REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | BLOB| DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | MEDIUMBLOB| FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | LONGBLOB| DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL] | TINYTEXT [BINARY]| NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL] [CHARACTER SET charset_name] [COLLATE collation_name]| DATE | TEXT [BINARY]| TIME [CHARACTER SET charset_name] [COLLATE collation_name]| TIMESTAMP | MEDIUMTEXT [BINARY]| DATETIME [CHARACTER SET charset_name] [COLLATE collation_name]| YEAR | 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
  • NULL y valores de fábrica NULL | NOT NULL DEFAULT valor
  • Alterar una tablaALTER TABLE jugador ADD COLUMNuniverso VARCHAR(20) NOT NULL AFTERnombre;ALTER TABLE jugador DROP COLUMNuniverso;ALTER TABLE jugador ADD KEY universo; http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
  • Eliminar una tablaDROP TABLE jugador;
  • 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
  • Foreign Keys Una vez creada la tabla: ALTER TABLE jugador ADD FOREIGN KEY index_name (index_col_name) reference_def nition i
  • CASCADE ON UPDATE ON DELETE
  • INSERTINSERT [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] ... ]
  • DELETEDELETE [LOW_PRIORITY] [QUICK][IGNORE] FROM tbl_name [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
  • UPDATEUPDATE [LOW_PRIORITY] [IGNORE]table_reference SET col_name1={expr1|DEFAULT} [,col_name2={expr2|DEFAULT}] ... [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
  • REPLACEREPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr |DEFAULT},...),(...),...
  • INSERT ON DUPLICATE KEYINSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
  • TRUNCATETRUNCATE [TABLE] tbl_name
  • 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}
  • LOCKLOCK TABLES tbl_name [[AS] alias] lock_type [, tbl_name [[AS] alias] lock_type] ...lock_type: READ [LOCAL] | [LOW_PRIORITY] WRITEUNLOCK TABLES
  • Consultas a múltiples tablas JOIN Subquery
  • JOINSELECT t1.name, t2.salary FROM employee t1 INNER JOIN info t2ON t1.name = t2.nameSELECT t1.name, t2.salay FROM employee t1, info t2 WHEREt1.name = t2.name
  • Tipos de JOIN table_reference [INNER | CROSS] JOINtable_factor [join_condition] | table_reference STRAIGHT_JOINtable_factor | table_reference STRAIGHT_JOINtable_factor ON conditional_expr | table_reference {LEFT|RIGHT} [OUTER]JOIN table_reference join_condition | table_reference NATURAL [{LEFT|RIGHT}[OUTER]] JOIN table_factor
  • SubqueriesSELECT * FROM t1 WHERE column1 =(SELECT column1 FROM t2);
  • VistasCREATE [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]
  • ProcedimientosCREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name([proc_parameter[,...]]) [characteristic ...] routine_body
  • TriggersCREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_timetrigger_event ON tbl_name FOR EACH ROWtrigger_body
  • Caso práctico
  • Ejercicio Crear las tablas del siguiente diagrama Crear las vistas asociadas (SELECT) Insertar una Notif cación al insertar una i nueva tarea (TRIGGER) Crear un procedimiento “tarea_notif cada” i (STORED PROCEDURE) que elimine la notif cación y ponga la tarea en el estado i “progreso”
  • Diseño orientativo