Comando Mysql

 
 
Microsoft Windows [Versión 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Reservados todos los derechos.

C:\Users\01062-10>cd/xampp/mysql/bin

C:\xampp\mysql\bin> mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.11 MySQL Community Server (GPL)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databasees;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'datab
asees' at line 1
mysql>
mysql>
mysql>
mysql>
mysql>
mysql>
mysql>
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| cdcol              |
| data               |
| mysql              |
| performance_schema |
| phpmyadmin         |
| test               |
| webauth            |
+--------------------+
8 rows in set (0.15 sec)

mysql> create
    -> sintaxis
    -> create database nombre de la B.D;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'sinta
xis
create database nombre de la B.D' at line 2
mysql> create
    -> create biblioteca;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'creat
e biblioteca' at line 2
mysql> create
    -> create database biblioteca;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'creat
e database biblioteca' at line 2
mysql> create
    -> sintaxis
    -> create database biblioteca;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'sinta
xis
create database biblioteca' at line 2
mysql> create database biblioteca;
Query OK, 1 row affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| biblioteca         |
| cdcol              |
| data               |
| mysql              |
| performance_schema |
| phpmyadmin         |
| test               |
| webauth            |
+--------------------+
9 rows in set (0.00 sec)

mysql> use biblioteca
Database changed
mysql> use biblioteca;
Database changed
mysql> chow tables;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'chow
tables' at line 1
mysql> show tables;
Empty set (0.00 sec)

mysql> create table libro
    -> (cod-lib char(10)not null primary key,
    ->
    -> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '-lib
char(10)not null primary key,' at line 2
mysql> create table libro
    -> (cod_lib char(10)not null primary key,
    -> nom_lib char(40) not null);
Query OK, 0 rows affected (0.30 sec)

mysql>
cmd


Microsoft Windows [Versión 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Reservados todos los derechos.

C:\Users\01062-10>cd/xampp/mysql/bin

C:\xampp\mysql\bin> mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.11 MySQL Community Server (GPL)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databasees;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'datab
asees' at line 1
mysql>
mysql>
mysql>
mysql>
mysql>
mysql>
mysql>
mysql> show databases; sirve para ver las bases de datos que se llevan hasta el momento
+--------------------+
| Database           |
+--------------------+
| information_schema |
| cdcol              |
| data               |
| mysql              |
| performance_schema |
| phpmyadmin         |
| test               |
| webauth            |
+--------------------+
8 rows in set (0.15 sec)

mysql> create
    -> sintaxis
    -> create database nombre de la B.D;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'sinta
xis
create database nombre de la B.D' at line 2
mysql> create
    -> create biblioteca;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'creat
e biblioteca' at line 2
mysql> create
    -> create database biblioteca;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'creat
e database biblioteca' at line 2
mysql> create
    -> sintaxis
    -> create database biblioteca;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'sinta
xis
create database biblioteca' at line 2
mysql> create database biblioteca;
Query OK, 1 row affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| biblioteca         |
| cdcol              |
| data               |
| mysql              |
| performance_schema |
| phpmyadmin         |
| test               |
| webauth            |
+--------------------+
9 rows in set (0.00 sec)

mysql> use biblioteca
Database changed
mysql> use biblioteca;
Database changed
mysql> chow tables;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'chow
tables' at line 1
mysql> show tables;
Empty set (0.00 sec)

mysql> create table libro
    -> (cod-lib char(10)not null primary key,
    ->
    -> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '-lib
char(10)not null primary key,' at line 2
mysql> create table libro
    -> (cod_lib char(10)not null primary key,
    -> nom_lib char(40) not null);
Query OK, 0 rows affected (0.30 sec)

mysql> show table
    ->
    -> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '' at
line 1
mysql>
mysql>
mysql> show tables;
+----------------------+
| Tables_in_biblioteca |
+----------------------+
| libro                |
+----------------------+
1 row in set (0.00 sec)

mysql> decribe libro;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'decri
be libro' at line 1
mysql> describe libro;
+---------+----------+------+-----+---------+-------+
| Field   | Type     | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| cod_lib | char(10) | NO   | PRI | NULL    |       |
| nom_lib | char(40) | NO   |     | NULL    |       |
+---------+----------+------+-----+---------+-------+
2 rows in set (0.04 sec)

mysql> create table autor
    -> (cod_aut char(10) not null primary key,
    -> nom_aut char(40) not null);
Query OK, 0 rows affected (0.15 sec)

mysql> show tables;
+----------------------+
| Tables_in_biblioteca |
+----------------------+
| autor                |
| libro                |
+----------------------+
2 rows in set (0.00 sec)

mysql> describe autor;
+---------+----------+------+-----+---------+-------+
| Field   | Type     | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| cod_aut | char(10) | NO   | PRI | NULL    |       |
| nom_aut | char(40) | NO   |     | NULL    |       |
+---------+----------+------+-----+---------+-------+
2 rows in set (0.03 sec)

mysql> create fable lib_aut
    -> (cod_lib char(10) not null,
    -> cod_aut char(10) not null,
    -> foreign key(cod_lib) references libro(cod_lib)
    -> on delete cascade on update cascade,
    -> foreign key(cod_aut) references autor(cod_aut)
    -> on delete cascade on update cascade);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'fable
lib_aut
(cod_lib char(10) not null,
cod_aut char(10) not null,
foreign key' at line 1
mysql> showm tables;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'showm
tables' at line 1
mysql>
mysql>
mysql> create fable lib_aut
    -> (cod_lib char(10) not null,
    -> cod_aut char(10) not null,
    -> foreign key (cod_lib)
    -> references libro(cod_lib)
    -> on delete cascade on update cascade,
    -> foreign key (cod_aut) reference;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'fable
lib_aut
(cod_lib char(10) not null,
cod_aut char(10) not null,
foreign key' at line 1
mysql> create fable lib_aut
    -> (cod_lib char(10) not null,
    -> cod_aut char(10) not null,
    -> foreign key(cod_lib) references libro(cod_lib) on delete cascade on updet
e cascade,
    -> foreign key(cod_aut) references autor(cod_aut) on delete cascade on updet
e cascade);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'fable
lib_aut
(cod_lib char(10) not null,
cod_aut char(10) not null,
foreign key' at line 1
mysql> create table lib_aut
    -> (cod_lib char(10) not null,
    -> cod_aut char(10) not null,
    -> foreign key(cod_lib) references libro(cod_lib) on delete cascade on updet
e cascade,
    -> foreign key(cod_aut) references autor(cod_aut) on delete cascade on updet
e cascade);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'updet
e cascade,
foreign key(cod_aut) references autor(cod_aut) on delete cascade' at line 4
mysql> create fable lib_aut
    -> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'fable
lib_aut' at line 1
mysql> create table lib_aut
    -> (cod_lib char(10) not null,
    -> cod_aut char(10) not null,
    -> foreign key(cod_lib) references libro(cod_lib) on delete cascade on updat
e cascade,
    -> foreign key(cod_aut) references autor(cod_aut) on delete cascade on updat
e cascade);
Query OK, 0 rows affected (0.28 sec)

mysql> exit

bye
C:\xampp\mysql\bin>mysqldump -B -uroot -p biblioteca> d:/biblioteca.sql
 
Enter password:
 
 
CLASE 15/03/2014
 
Como restaurar 
 
 
2. use biblioteca y visualizar tablas:
 
3. visualizar tablas:
 
 
4. agragar campos y visualizar:
 
 
 
5. eliminar campos:
 
 
6. modificar tamaño del campo:
 
 
7. cambiar nombre de un campo:
 
 
8. Eliminar clave primaria:
 
 
9. Modificar clave primaria
 
 
 
 
C:\xampp\mysql\bin>
C:\xampp\mysql\bin>


 

Comandos Mysql

Requisitos para ingresar a mysql:
 
1. Abrir xampp, panel de control de xampp y activamos apache y mysql:
 
2. Abrimos cmd y digitamos (cd/xampp/mysql/bin) y enter:
 
 
3. Digitamos (mysql -uroot -p): 
 
 
Ahora se indicaran algunos comandos de bases de datos:
 
- create database nombre_base_datos; ----------------------------------------------- (Crea una base de datos)
- show databases; ----------------------------------------------------------------------------- (Muestra las bases de datos que hay en el pc)
- show tables; ----------------------------------------------------------------------------------- (Muestra las tablas de la base de datos seleccionada)
- show nombre_tabla status; -------------------------------------------------------------- (Muestra la informacion sobre las tablas de la base de datos)
- create table nombre_tabla; -------------------------------------------------------------- (Crea una tabla en la base de datos que este seleccionada)
Ejemplo
- describe nombre_tabla; ---------------------------------------------------------- (Muestra la estructura de la tabla (filas y comlumnas)
- select * from nombre_tabla; --------------------------------------------------- (Nos muestra los datos que hay ingresados en la tabla)
- select * from nombre_tabla limit numero_inicio,numero_final;----- (Nos muestra los datos que hay ingresados en la tabla con ese limite)
- use nombre_base_datos; ------------------------------------------------------ (Selecciona una base de datos para su uso)
- drop nombre_tabla; --------------------------------------------------------------- (Elimina la tabla incluyendo registros y estructura)
- drop nombre_tabla if exist; ---------------------------------------------------- (Elimina la tabla de la base de datos pero antes verifica que existe)
- truncate nombre_tabla; --------------------------------------------------------- (Elimina los registros pero mantiene la estructura de la tabla)
- alter table nombre_tabla rename to nombre_nuevo;------------------ (Alter table nos referencia la tabla para poder renombrarla)
- check nombre_tabla; ------------------------------------------------------------ (Checkea la tabla o tablas por errores)
- repair nombre_tabla; ------------------------------------------------------------- (Repara una tabla posiblemente corrupta)
 

Relacionar tablas

Relacion

Para hacer una copia de seguridad

1. Nos salimos de Mysql presionando exit.
2. Ya en el directorio bin en el cmd digitamos (mysqldump -B -uroot -p nombre_base_datos > D:/ Nuevo_nombre.sql
 

Agregar campos

1. Alter table nombre_tabla add campo tipo_requeridoo_no;
Ejemplo
-alter table libro add valor_lib int(7) not null;--------------------------- Inserta al final de la tabla
-alter table lirbo add editorial char(20) not null;-----------------------Insertar despues de.
 
-alter table lirbo add tomo_lib char(2) not null first;-----------------Insertar al principio.
 

Eliminar campos de una tabla

-alter table nombre_tabla drop campo_eliminar;--------------------Elimina el campo de una tabla.
Ejempo
-alter table libro dop tomo_libro;

Modificar el tamaño de un campo

-alter table nombre_tabla modify nombre_campo tipo(nuevo_tamaño) not null;
Ejemplo
-alter table libro modify nom_lib char(50) not null;
 
 

Cambiar nombre de un campo

- alter table nombre_tabla change nombre_campo nuevo_nombre;
Ejemplo
-alter table libro change valor_lib presio_lib int(7) not null;
 

Eliminar clave primaria

-alter table nombre_tabla drop primary key;
Ejemplo
-alter table libro drop primary key;

Se crea una nueva tabla 

Se elimina su clave primaria:
-alter table editorial drop primary key;
 

Definir otra clave primaria

-alter table nombre_tabla modify nombre_campo tipo(tamaño) requerido_o_no primary key;
Ejemplo
-alter table editorial modify nombre_editorial char(40) not null primary key;
 

Renombrar o cambiar el nombre de una tabla

-alter table nombre_tabla rename to nuevo_nombre;
Ejemplo
-alter table editorial rename editorial_libro;
 

Eliminar una tabla

-drop table nombre_tabla;
Ejemplo
-drop table editorial_libro;
 
 

Eliminar base de datos

-drop table nombre_tabla;
Ejemplo
-drop database nombre_base de datos;
 
 

Insertar informacion a los campos de una tabla

-insert into nombre_tabla(campo_1,campo_2.......campo_n) values (valor campo_1, valor campo_2........, valor campo_n);
Ejemplo
-insert into libro(cod_lib,nom_lib,editorial) values (valor campo_1, valor campo_2........, valor campo_n); ("Si el valor del campo a insertar es tipo texto debe ir entre comillas sencillas 'hola')
 
 

Para visualizar un comando individual

 

Para visualizar informacion

-select * from nombre_tabla;
-select campo1,campo2..campoN from nombre_tabla;
Ejemplo
select * from libro;
 

Actualizar o corregir informacion en un registro (Para actualizar o modificar contenido de un campo)

-update nombre_tabla set campo=nueva_informacion condicion;
Ejemplo
update libro set nombre='lo que el viento se llevo' where cod_lib='0001';
 

Condicionales

-AND
-OR
-LIKE ('%a'),('a%'),('%a%').
-BETWEEN
-IN
-<,>,<=,>=,<>,=
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Visualizar datos o informacion

1. Leer.
2. Saber que se va a visualizar.
3. Saber que tabla o tablas va utilizar el comando.
4. Condiciones.
5. Comando y sintaxis para resolverlo.

Copia de seguridad

 

Funciones para calculos

-Sum (numerico)
-Max (numerico)
-Min (numerico)
-Avg (numerico)
-Count (numerico y texto)
 
Sintaxis:
-Select funcion (valor) 'texto' from tabla;
 
Sintaxis
-Select sum(total) 'valor total de los libros' from libro;
Sintaxis para contar la cantidad de registros de la base de datos
-select count(nom_lib) 'Cantidad de registros de la base de datos' from libro;
 
Sintaxis para hallar el presio maximo de un libro
- select max(presio_lib) 'Precio del libro mas caro' from libro;
Para mostrar mas que el precio del libro
 
-select nom_lib,presio_lib, max(presio_lib) 'Libro mas costoso' from libro;
 
Promedio de libros que hay en la biblioteca
 
-select avg(cant) 'Promedio de los libros existentes' from libro;
 
Ejemplo
.update libro set total=cant*presio_linb;
 
 

Eliminar datos de una tabla

DELETE FROM tabla WHERE condición
Ejemplo
-DELETE FROM fichajes WHERE fecha = '2012-07-07';
 

Ordenar datos

comando
-order by
Ejemplo
-Select * from tabla condicion order by campo_ordenar tipo_ordenado (ascendeto o descendente);
-select * from autor order by nombre;

Insertar en una tabla relacional

 

Ordenar descendentemente (ascendentemente por defecto)

 -select * from autor order by nombre desc;
 

Exportar a excel

 -select * from autor order by nombre desc into outfile 'D:/ordenautas.xls';
 -select * from autor order by nombre desc into outfile 'D:/ordenautas2.csv';
 

Ordenar la tabla libro de forma ascendente por los campos editorial y nombre del libro, visualizando solo los siguientes datos, codigo del libro, nombre del libro y la editorial

 

Consultas relacionales

Analisis
1. Que deseamos mostrar (tablas).
2. Que tablas se ven afectadas.
3. Condiciones en particular (logica).
4. Como se relaciona una tabla con la otra.
5. Comando que da la solucion.
 
 
Ejemplo
1. el cod_lib,nom_lib(tabla libro), el nombre(tabla autor), el cod_lib,cod_aut(tabla lib_autor).
2. libro,autor,lib_autor.
3. que nom_lib sea igual a 'lo que el viento se llevo.
4. que (libro.cod_lib sea igual a lib_aut.cod_lib) y que (lib_aut.cod_aut=autor.cod_aut).
5. (visualizar,mostrar, consultas) select.
 
 

Comando autoincrement

-Permite crear campos que se autoincrementan
AUTOMATICA/...
Ejemplo
Crear una tabla utilizando el comando:
Descripcion:
Insertar dato:

Eliminar informacion o registros

delete from edicion where codigo='1'; 
 
Insertar edicion 5
insertar edicion 1 de nuevo (consecutivo)
Para poder volver a insertar el consecutivo se utiliza el comando truncate (borra datos de la tabla y la deja como acabada de crear)
Ejemplo
-truncate table edicion;
Insertar informacion de nuevo
 

Instruccion Unsigned

Se crea una tabla nueva:
Ingreso de algunos datos
Para evitar a un campo se le ingresen valores negativos se utiliza unsigned
Update a datos:
 

Comando group by

Este comando sirve para agrupar registros para consultas detalladas
Sintaxis
-select * from tabla group by nombre_campo(s);
Ejemplo: 
Hallar el monto compra por ciudad.
as: sirve para poner un mensaje alterno en el resultado de la consulta.
-select ciudad,sum(montocompra) as total from visitantes group by ciudad;
Ejemplo:
Hallar el monto de compra por ciudad que sean mayores a 5 millones
-comando having
-select ciudad,sum(montocompra) as total from visitantes group by ciudad having sum(montocompra)>5000000;
Ejemplo:
Visualizar las ciudades a las que van mas de dos visitantes