insert into actor (first_name, last_name) values ('juan','perez'); insert into actor (first_name, last_name) values ('rosa','pi'); update actor set first_name='PEPE' where actor_id=10; update actor set first_name=concat('Actor',actor_id) where actor_id>200; delete from actor where actor_id>200; select country, customer.* from country join city on country.country_id=city.country_id join address on city.city_id=address.city_id join customer on address.address_id=customer.address_id where country like 'A%'; select country.country, customer.* from customer join address on customer.address_id=address.address_id join city on address.city_id=city.city_id join country on city.country_id=country.country_id where country like 'a%'; select distinct first_name,last_name from actor join film_actor on actor.actor_id=film_actor.actor_id join film on film_actor.film_id=film.film_id where length>140; select distinct name from category join film_category on category.category_id=film_category.category_id join film on film_category.film_id=film.film_id where rating='r'; select title, count(rental_id) total from film join inventory on film.film_id=inventory.film_id join rental on inventory.inventory_id=rental.inventory_id group by film.film_id having total>20; select country.country, customer.* from customer join address on customer.address_id=address.address_id join city on address.city_id=city.city_id join country on city.country_id=country.country_id where country ='spain' or country='argentina'; select country.country, customer.* from customer join address on customer.address_id=address.address_id join city on address.city_id=city.city_id join country on city.country_id=country.country_id where country in ('spain','argentina'); select title, name from category join film_category on category.category_id=film_category.category_id join film on film_category.film_id=film.film_id where name in ('children','family'); select first_name, last_name from actor where first_name like '%x%' or last_name like '%x%'; select * from address where district='california' and phone like '%274%';
Autor: Juan Pablo Fuentes
Ejemplos agregados
-- El total de ciudades: contar select country,count(city) total from country join city on country.country_id=city.country_id group by country; -- Total de importe de clientes select first_name, last_name, sum(amount) total, avg(amount) media, count(amount) numero, max(amount) maximo, min(amount) minimo from customer join rental on customer.customer_id=rental.customer_id join payment on rental.rental_id=payment.rental_id group by customer.customer_id; -- en la consulta anterior los clientes que han gastado más de 100 dolares select first_name, last_name, sum(amount) total, avg(amount) media, count(amount) numero, max(amount) maximo, min(amount) minimo from customer join rental on customer.customer_id=rental.customer_id join payment on rental.rental_id=payment.rental_id group by customer.customer_id having total>100; -- Los clientes cuyo nombre empieza por 'a' que han gastado más de 100 dolares select first_name, last_name, sum(amount) total, avg(amount) media, count(amount) numero, max(amount) maximo, min(amount) minimo from customer join rental on customer.customer_id=rental.customer_id join payment on rental.rental_id=payment.rental_id where first_name like 'a%' group by customer.customer_id having total>100 and media>4; -- ¿Cuantos países tienen más de 50 clientes? -- Nombre del país y número de clientes (count) select country, count(customer_id) total from country join city on country.country_id=city.country_id join address on city.city_id=address.city_id join customer on address.address_id=customer.address_id group by country.country_id having total>50
Ejemplos select
-- Para cada país sus ciudades -- join me está diciendo que relaciono las dos tablas -- on me dirá mediante que campos están relacionados select country,city from country join city on country.country_id=city.country_id; select country,city from country co join city ci on co.country_id=ci.country_id; -- Solo vale para mysql y el campo se tiene que llamar igual select country,city from country join city using(country_id); select country,city,first_name,last_name from country join city on country.country_id=city.city_id join address on city.city_id=address.city_id join customer on address.address_id=customer.address_id; select name,title from category join film_category on category.category_id=film_category.category_id join film on film_category.film_id=film.film_id; -- left join nos dice que devolvamos los valores de la tabla de la izquierda -- Aunque no tengamos valores relacionados select name,title from category left join film_category on category.category_id=film_category.category_id left join film on film_category.film_id=film.film_id; -- right join nos dice que devolvamos los valores de la tabla de la derecha -- Aunque no tengamos valores relacionados select name,title from category right join film_category on category.category_id=film_category.category_id right join film on film_category.film_id=film.film_id
Sakila esquema
Insert de revistas
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Nature’, ‘1234-5678’, 1, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Science’, ‘5678-1234’, 2, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘The New England Journal of Medicine’, ‘8765-4321’, 3, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘The Lancet’, ‘4321-8765’, 4, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Cell’, ‘9876-5432’, 5, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Nature Reviews Immunology’, ‘5432-9876’, 6, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Journal of the American Medical Association’, ‘2345-6789’, 7, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Nature Genetics’, ‘6789-2345’, 8, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘The Astrophysical Journal’, ‘3456-7890’, 9, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘IEEE Transactions on Neural Networks and Learning Systems’, ‘7890-3456’, 10, 2023);
Catálogo revistas
DROP TABLE IF EXISTS `revista` ;
CREATE TABLE IF NOT EXISTS `revista` (
`idrevista` INT NOT NULL AUTO_INCREMENT,
`titulo` VARCHAR(100) NOT NULL,
`issn` CHAR(9) NOT NULL,
`numero` INT NOT NULL,
`anyo` YEAR NOT NULL,
PRIMARY KEY (`idrevista`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `articulo` ;
CREATE TABLE IF NOT EXISTS `articulo` (
`idarticulo` INT NOT NULL AUTO_INCREMENT,
`titulo` VARCHAR(100) NOT NULL,
`inicio` INT NOT NULL,
`final` INT NOT NULL,
`idrevista` INT NOT NULL,
PRIMARY KEY (`idarticulo`),
CONSTRAINT `idrevista`
FOREIGN KEY (`idrevista`)
REFERENCES `revista` (`idrevista`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
CREATE INDEX `idrevista_idx` ON `articulo` (`idrevista` ASC) VISIBLE;
DROP TABLE IF EXISTS `autor` ;
CREATE TABLE IF NOT EXISTS `autor` (
`idautor` INT NOT NULL AUTO_INCREMENT,
`nombre` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`pais` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idautor`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `articulo_autor` ;
CREATE TABLE IF NOT EXISTS `articulo_autor` (
`idarticulo_autor` INT NOT NULL AUTO_INCREMENT,
`idautor` INT NOT NULL,
`idarticulo` INT NOT NULL,
`posicion` INT NOT NULL,
PRIMARY KEY (`idarticulo_autor`),
CONSTRAINT `idarticulo`
FOREIGN KEY (`idarticulo`)
REFERENCES `articulo` (`idarticulo`),
CONSTRAINT `idautor`
FOREIGN KEY (`idautor`)
REFERENCES `autor` (`idautor`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
CREATE INDEX `idarticulo_idx` ON `articulo_autor` (`idarticulo` ASC) VISIBLE;
CREATE INDEX `idautor_idx` ON `articulo_autor` (`idautor` ASC) VISIBLE;
Modelos ER
Solucion Solid
package com.trifulcas.juegoPPTLSID; import java.util.Arrays; public class JuegoColores implements ILogica{ private String[] jugadas = { "verde","azul","amarillo","naranja","rojo" }; public JuegoColores() { } @Override public int comprobar(String jugada1, String jugada2) { int pos1 = Arrays.asList(jugadas).indexOf(jugada1.toLowerCase()); int pos2 = Arrays.asList(jugadas).indexOf(jugada2.toLowerCase()); if ((pos1 + 1) % jugadas.length == pos2) return 1; if ((pos2 + 1) % jugadas.length == pos1) return 2; return 0; } @Override public String[] validas() { return this.jugadas; } } package com.trifulcas.juegoPPTLSID; public interface IMostrar { void mostrar(String res); } package com.trifulcas.juegoPPTLSID; public class Juego { private Jugador jugador1; private Jugador jugador2; private ILogica _iLogica; private IMostrar _iMostrar; private String[] jugadas; public String[] getJugadas() { return jugadas; } public void setJugadas(String[] jugadas) { this.jugadas = jugadas; } public Jugador getJugador1() { return jugador1; } public void setJugador1(Jugador jugador1) { this.jugador1 = jugador1; } public Jugador getJugador2() { return jugador2; } public void setJugador2(Jugador jugador2) { this.jugador2 = jugador2; } public Juego(Jugador jugador1, Jugador jugador2, ILogica ilogica, IMostrar imostrar) { this.jugador1 = jugador1; this.jugador2 = jugador2; _iLogica = ilogica; jugadas = _iLogica.validas(); _iMostrar = imostrar; } public Juego(Jugador jugador1, Jugador jugador2, ILogica ilogica) { this(jugador1, jugador2, ilogica, new Consola()); } public String jugar() { jugador1.pedirJugada(jugadas); jugador2.pedirJugada(jugadas); _iMostrar.mostrar(jugador1.getNombre() + " elige " + jugador1.getJugada()); _iMostrar.mostrar(jugador2.getNombre() + " elige " + jugador2.getJugada()); int res = _iLogica.comprobar(jugador1.getJugada(), jugador2.getJugada()); String resultado="Empate"; if (res == 1) { resultado= jugador1.getNombre(); } if (res == 2) { resultado= jugador2.getNombre(); } _iMostrar.mostrar(resultado); return resultado; } } package com.trifulcas.juegoPPTLSID; public class Consola implements IMostrar { @Override public void mostrar(String res) { System.out.println(res); } } package com.trifulcas.juegoPPTLSID; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class Fichero implements IMostrar { @Override public void mostrar(String res) { Path path = Paths.get("resultado.txt"); try { if (!Files.exists(path)) Files.createFile(path); Files.writeString(path, res+"\r\n", StandardOpenOption.APPEND); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Soluciones ejercicios SOLID
package com.trifulcas.ejerciciosSolid; public class Article { private String Title; private String Content; public void setTitle(String title) { this.Title = title; } public void setContent(String content) { this.Content = content; } } package com.trifulcas.ejerciciosSolid; public class GenerateSummary { public String generateSummary(String content) { // Logic to generate a summary from the content return content.substring(0, 100) + "..."; // just a simple example } } package com.trifulcas.ejerciciosSolid; import com.trifulcas.juego.Enemigo; public class SaveToDatabase { // Cosas del tipo conexión a BD // etc... public void saveToDatabase(Article article) { // Logic to save the article to a database } public void saveToDatabase(Enemigo enemigo) { // Logic to save the article to a database } } package com.trifulcas.ejerciciosSolid; public abstract class ReportGenerator { public abstract void generateReport(String data); } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorPDF extends ReportGenerator { @Override public void generateReport(String data) { System.out.println("Aquí va el código de generar PDF"); } } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorCSV extends ReportGenerator { @Override public void generateReport(String data) { System.out.println("Código para generar CSV"); } } package com.trifulcas.ejerciciosSolid; public interface IReportGenerator { public void generateReport(String data); } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorXML implements IReportGenerator { @Override public void generateReport(String data) { System.out.println("Lógica para generar XML"); } } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorID { IReportGenerator reportGenerator; public ReportGeneratorID(IReportGenerator reportGenerator) { this.reportGenerator = reportGenerator; } public void generateReport(String data) { reportGenerator.generateReport(data); } } package com.trifulcas.ejerciciosSolid; public class ProbarReports { public static void main(String[] args) { String datos="Hola que tal"; // Generar un PDF ReportGeneratorPDF rgp=new ReportGeneratorPDF(); rgp.generateReport(datos); // Generar un XML con ID ReportGeneratorXML rgx=new ReportGeneratorXML(); ReportGeneratorID rgid=new ReportGeneratorID(rgx); rgid.generateReport(datos); rgid=new ReportGeneratorID(rgx); rgid.generateReport(datos); } } package com.trifulcas.ejerciciosSolid; public interface IClean { void Clean(); } package com.trifulcas.ejerciciosSolid; public class Apartment implements IClean { @Override public void Clean() { System.out.println("Apartment cleaned."); } } package com.trifulcas.ejerciciosSolid; import java.util.Date; public interface IRoom { void Reserve(Date from, Date to); void CheckInventory(); } package com.trifulcas.ejerciciosSolid; public interface IInventory { void CheckInventory(); } package com.trifulcas.ejerciciosSolid; import java.util.Date; public interface IReserve { void Reserve(Date from, Date to); }
Piedra Papel Tijeras
https://github.com/juanpablofuentes/Java/tree/master/PiedraPapelTijera