SlideShare a Scribd company logo
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
Introducción rápida a SQL
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
Query
SELECT                                      [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_expr
UNKNOWN}
 | 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 datos
CREATE 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 datos
DROP DATABASE pruebas;
Cargar y guardar volcados
 Base de datos     Fichero
   MySQLdump
 Fichero    Base de datos
   Ejecutar sentencias SQL
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
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 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
Eliminar una tabla
DROP 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
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] ... ]
DELETE
DELETE [LOW_PRIORITY] [QUICK]
[IGNORE] FROM tbl_name
   [WHERE where_condition]
   [ORDER BY ...]
   [LIMIT row_count]
UPDATE
UPDATE [LOW_PRIORITY] [IGNORE]
table_reference
   SET col_name1={expr1|DEFAULT} [,
col_name2={expr2|DEFAULT}] ...
   [WHERE where_condition]
   [ORDER BY ...]
   [LIMIT row_count]
REPLACE
REPLACE [LOW_PRIORITY | DELAYED]
  [INTO] tbl_name [(col_name,...)]
  {VALUES | VALUE} ({expr |
DEFAULT},...),(...),...
INSERT ON DUPLICATE KEY
INSERT INTO table (a,b,c) VALUES (1,2,3)
 ON DUPLICATE KEY UPDATE c=c+1;
TRUNCATE
TRUNCATE [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}
LOCK
LOCK TABLES
  tbl_name [[AS] alias] lock_type
  [, tbl_name [[AS] alias] lock_type] ...

lock_type:
    READ [LOCAL]
  | [LOW_PRIORITY] WRITE

UNLOCK TABLES
Consultas a múltiples tablas
 JOIN
 Subquery
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
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
Subqueries
SELECT * FROM t1 WHERE column1 =
(SELECT column1 FROM t2);
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]
Procedimientos
CREATE
   [DEFINER = { user | CURRENT_USER }]
   PROCEDURE sp_name
([proc_parameter[,...]])
   [characteristic ...] routine_body
Triggers
CREATE
    [DEFINER = { user | CURRENT_USER }]
    TRIGGER trigger_name trigger_time
trigger_event
    ON tbl_name FOR EACH ROW
trigger_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

More Related Content

PPT
My sql presentation
PDF
MySQL partitions tutorial
PDF
The Origin of Lithium
PDF
Lithium: The Framework for People Who Hate Frameworks
PDF
A Tour to MySQL Commands
PDF
PHP 5.3 and Lithium: the most rad php framework
PDF
Agile database access with CakePHP 3
ODP
Patterns for slick database applications
My sql presentation
MySQL partitions tutorial
The Origin of Lithium
Lithium: The Framework for People Who Hate Frameworks
A Tour to MySQL Commands
PHP 5.3 and Lithium: the most rad php framework
Agile database access with CakePHP 3
Patterns for slick database applications

What's hot (20)

PDF
Linguagem sql
PDF
The State of Lithium
PDF
Internationalizing CakePHP Applications
PDF
Ruby - Uma Introdução
PDF
Doctrine MongoDB ODM (PDXPHP)
PDF
Using Scala Slick at FortyTwo
PDF
Building Lithium Apps
PDF
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
PPT
Arrays in php
PDF
Future of HTTP in CakePHP
PPT
mysqlHiep.ppt
PPTX
PHP Functions & Arrays
PDF
Symfony2 - extending the console component
KEY
Refactor like a boss
PDF
Functional programming with php7
PPTX
ES6 and BEYOND
PDF
Slaying the Dragon: Implementing a Programming Language in Ruby
PDF
Syntactic sugar in Postgre SQL
PDF
PHP Data Objects
PDF
Dependency Injection with PHP and PHP 5.3
Linguagem sql
The State of Lithium
Internationalizing CakePHP Applications
Ruby - Uma Introdução
Doctrine MongoDB ODM (PDXPHP)
Using Scala Slick at FortyTwo
Building Lithium Apps
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Arrays in php
Future of HTTP in CakePHP
mysqlHiep.ppt
PHP Functions & Arrays
Symfony2 - extending the console component
Refactor like a boss
Functional programming with php7
ES6 and BEYOND
Slaying the Dragon: Implementing a Programming Language in Ruby
Syntactic sugar in Postgre SQL
PHP Data Objects
Dependency Injection with PHP and PHP 5.3
Ad

Similar to Introducción rápida a SQL (20)

PDF
New tsql features
PPTX
Unit_III_SQL-MySQL-Commands-Basic.pptx usefull
PPTX
СУБД осень 2012 Лекция 3
PPTX
SQL-MySQL-Commands-Basic.pptx
PPTX
SQL Basics Commands for Class XII Students
PPT
SQL introduction
PDF
Simple Strategies for faster knowledge discovery in big data
PPT
Lecture-9-10-11-12(a-b).ppt modern database
PDF
Database Systems - SQL - DDL Statements (Chapter 3/2)
PPTX
Linguagem sql
PPTX
PPTX
Introducing ms sql_server_updated
PDF
Oracle APEX Cheat Sheet
PPT
Les09 (using ddl statements to create and manage tables)
PPT
PDF
My sql cheat sheet
PPTX
vFabric SQLFire Introduction
PPTX
Vertica-Database
PDF
Hadoop Summit EU 2014
PPTX
New tsql features
Unit_III_SQL-MySQL-Commands-Basic.pptx usefull
СУБД осень 2012 Лекция 3
SQL-MySQL-Commands-Basic.pptx
SQL Basics Commands for Class XII Students
SQL introduction
Simple Strategies for faster knowledge discovery in big data
Lecture-9-10-11-12(a-b).ppt modern database
Database Systems - SQL - DDL Statements (Chapter 3/2)
Linguagem sql
Introducing ms sql_server_updated
Oracle APEX Cheat Sheet
Les09 (using ddl statements to create and manage tables)
My sql cheat sheet
vFabric SQLFire Introduction
Vertica-Database
Hadoop Summit EU 2014
Ad

More from Carlos Hernando (8)

PDF
Introduciendo Serverless en Proyectos Python
PDF
Microservicos: Cuándo y Cómo
PDF
Try AngularJS
PDF
Django tricks (2)
PDF
Metodologías Ágiles
PDF
Bases de Datos en Java - Intro a Hibernate
PDF
Bases de Datos en Java - Intro a JDBC
PDF
Persistencia en Java - Serialización
Introduciendo Serverless en Proyectos Python
Microservicos: Cuándo y Cómo
Try AngularJS
Django tricks (2)
Metodologías Ágiles
Bases de Datos en Java - Intro a Hibernate
Bases de Datos en Java - Intro a JDBC
Persistencia en Java - Serialización

Recently uploaded (20)

PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Hybrid model detection and classification of lung cancer
PPTX
TLE Review Electricity (Electricity).pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Mushroom cultivation and it's methods.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Tartificialntelligence_presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
A Presentation on Artificial Intelligence
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Encapsulation theory and applications.pdf
OMC Textile Division Presentation 2021.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Enhancing emotion recognition model for a student engagement use case through...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Hybrid model detection and classification of lung cancer
TLE Review Electricity (Electricity).pptx
A comparative study of natural language inference in Swahili using monolingua...
Mushroom cultivation and it's methods.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
A novel scalable deep ensemble learning framework for big data classification...
cloud_computing_Infrastucture_as_cloud_p
Programs and apps: productivity, graphics, security and other tools
Tartificialntelligence_presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
A Presentation on Artificial Intelligence
Building Integrated photovoltaic BIPV_UPV.pdf
Zenith AI: Advanced Artificial Intelligence
A comparative analysis of optical character recognition models for extracting...
Encapsulation theory and applications.pdf

Introducción rápida a SQL

  • 1. Introducción rápida a SQL Usando MySQL y Workbench Carlos Hernando Carasol chernando@acm.org 5 y 9 de Mayo de 2011
  • 2. Índice de contenidos Introducción a las bases de datos Introducción a MySQL Sintaxis de SQL Uso de MySQL Worbench
  • 3. 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
  • 4. Introducción a las bases de datos
  • 5. 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
  • 6. 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
  • 8. Servidor MySQL Http://www.mysql.com/ Comprado por Oracle Disponible gratuitamente Muy extendido
  • 9. 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.
  • 10. 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
  • 11. MySQL Workbench Herramienta de gestión, consulta y diseño http://wb.mysql.com/ Lo utilizaremos como apoyo
  • 14. Tipos de sentencias De consulta: SHOW DESC SELECT De manipulación: CREATE INSERT UPDATE ALTER
  • 15. Obtener información de una tabla SHOW TABLES DESC tabla http://dev.mysql.com/doc/refman/5.1/en/describe.html
  • 16. Query SELECT [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
  • 17. 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_expr UNKNOWN} | boolean_primary http://dev.mysql.com/doc/refman/5.1/en/expressions.html
  • 18. Funciones AVG() CONCAT() COUNT() CURRENT_DATE() IF() TRIM() LOWER() http://dev.mysql.com/doc/refman/5.1/en/func-op-summary-ref.html
  • 19. Union Agregación de SELECT ... tablas UNION [ALL | Mismas columnas DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]
  • 20. Creación de una base de datos CREATE DATABASE curso;
  • 21. 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;
  • 22. Destruir una base de datos DROP DATABASE pruebas;
  • 23. Cargar y guardar volcados Base de datos Fichero MySQLdump Fichero Base de datos Ejecutar sentencias SQL
  • 24. 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
  • 25. Propiedades de una tabla Tipo de ENGINE MyISAM InnoDB Charset Latin1 UTF8
  • 26. Tipos de datos Numéricos Cadenas Binarios Tiempo
  • 27. 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
  • 28. Cadenas CHAR VARCHAR BLOB ENUM SET http://dev.mysql.com/doc/refman/5.1/en/string-types.html
  • 29. Binarios BINARY VARBINARY http://dev.mysql.com/doc/refman/5.1/en/binary-varbinary.html
  • 30. Tiempo DATETIME DATE TIME TIMESTAMP YEAR http://dev.mysql.com/doc/refman/5.1/en/date-and-time-types.html
  • 31. 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
  • 32. NULL y valores de fábrica NULL | NOT NULL DEFAULT 'valor'
  • 33. 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
  • 34. Eliminar una tabla DROP TABLE jugador;
  • 35. 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
  • 36. Foreign Keys Una vez creada la tabla: ALTER TABLE jugador ADD FOREIGN KEY index_name (index_col_name) reference_def nition i
  • 37. CASCADE ON UPDATE ON DELETE
  • 38. 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] ... ]
  • 39. DELETE DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
  • 40. UPDATE UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
  • 41. REPLACE REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
  • 42. INSERT ON DUPLICATE KEY INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
  • 44. 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}
  • 45. LOCK LOCK TABLES tbl_name [[AS] alias] lock_type [, tbl_name [[AS] alias] lock_type] ... lock_type: READ [LOCAL] | [LOW_PRIORITY] WRITE UNLOCK TABLES
  • 46. Consultas a múltiples tablas JOIN Subquery
  • 47. 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
  • 48. 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
  • 49. Subqueries SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
  • 50. 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]
  • 51. Procedimientos CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic ...] routine_body
  • 52. Triggers CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body
  • 54. 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”