Yo estoy haciendo ambas, la del mx y la del Metro de Medellín
que bien, me parece genial, super esta comparación
Para los que no ven 🙈 mejor que buscar la imagen, aquí están las líneas 👀
Ferrería -> Línea 6
Pantitlan - Línea 1, Línea 5, Línea 9, Línea A
Tacuba -> Línea 7, Línea 2
Martín Carrera -> Línea 4, Línea 6
Muchas Gracias Ivan :)
Descubrí que se pueden declarar funciones en SQL, así que me puse la tarea de crear una función con la que le pasara el id de la linea y el nombre de la estación que queria relacionar y me quedó así
DELIMITER//CREATEFUNCTIONinsertTuple2(id, nameToFilter)RETURNINTBEGININSERTINTO`metro_project`.`lines_stations`(line_id, station_id)VALUES(id,(SELECT id FROM`metro_project`.`stations`WHERE name=nameToFilter))RETURNNULLEND//DELIMITER;
Lo que me pareció mas interesante fue el DELIMITER (Ya que sirve para cambiar el simbolo que representa el fin de una linea en SQL) y lo determinante que es para que funcione correctamente la sentencia, me pase dos noches sin poder avanzar por no entenderlo. Espero les pique el bicho de la curiosidad.
Saludos
Ah, y si despues necesitan ejecutar la función, lo hacen con
SELECTinsertTuple2(1,'La estacion que quier agregar')
Pregunta no existe la forma de que se hagan mas sub_consultas y asi no buscar uno por uno. 😅
Espero poder sacar provecho de esté curso para inicarme como desarrollador para el metro de Bogota D.C.
Buen chascarrillo.
No va a haber metro en Bogotá por el tipo y forma del suelo, pero podrías hacer una iniciativa para algún metro flotante o algo así
Mi reto va a ser el Metro de Caracas (excluyendo a las zonas en construcción y el el metro de los Teques)
Para quienes lo esten haciendo del transmilenio Bogotá
Troncales
<A-Caracas||D-Cl80||G-NQS sur ||K-Cl26||B-Norte||E-NQS central ||H-Caracas sur ||L-kr 10||C-Suba||F-americas ||J-Eje ambiental ||M-Kr7>
<Polo||Escuela militar || cra 47|| cra 53|| av 68||Ferias||Boyacá||Minuto de Dios||Granja-cra 77|| av cali || cra 90||Quirigua||Portal de la 80>
G
<Comuneros||Santa isabel ||SENA||NQS-cll 30 s ||NQS-cll 38-a s ||GeneralSantander||Alquería||Venecia||Sevillana||Madelena||Perdomo||Portal del sur ||Bosa||La despensa ||LeónXIII||Terreros-hospitalC.V||SanMateo>
K
<Universidades||Centro memoria ||Plaza deLaDemocracia ||Ciudad universitaria ||Corferias||Quinta paredes ||Gobernación||CAN||Salitre-el greco ||El tiempo-maloka || av rojas ||Normandía||Modelia||Portal el Dorado||Aereopuerto elDorado
>
B
<cll 85||Virrey|| cll 100|| cll 106||Pepe sierra || cll 127||Prado||Alcalá|| cll 142|| cll 146||Mazurén||Cardio infantil ||Toberín||Portal del norte || cll 187||Terminal>
E
<Tigua-san Jose||Guatoque-veraguas ||Ricaurte||Paloquemao||CAD|| av el Dorado||U nacional ||CampinUAntonioNariño||Coliseo||SimónBolívar|| av Chile||NQS-cll 75||La castellana
>
H
<Hospital||Nariño||Fucha||Restrepo||Olaya||Quiroga|| cll 40 s ||SantaLucía||Socorro||Consuelo||Molinos||PortalUsme||Biblioteca||Parque||Portal del Tunal>
L
<Portal20 de Julio||Country sur || av 1 de Mayo||Ciudad jardin-UAN||Policarpa||Hospitales||Bicentenario||San victorino ||Las nieves ||SanDiego>
C
<SanMartin||Rio negro ||Suba-cll 95||Suba-cll 100||Puente largo ||Shaio||Humedal córdoba ||Niza-cll 127||Suba-av Boyacá||Gratamira||21 Ángeles ||Suba-tv 91||La campiña ||Portal de suba
>
A alguien le salió el error Error Code: 1242. Subquery returns more than 1 row en el workbench al poner un registro que es único para una sola línea del metro? No sé cómo resolverlo :(
Para el campo de updated_at existe un EXTRA para que se vaya actualizando cada vez que se modifica un registro de la tabla ON UPDATE.
USE metro_cdmx;
-- make the 'lines_stations' pivot table
CREATE TABLE `lines_stations` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`line_id` BIGINT(20) UNSIGNED NOT NULL,
`station_id` BIGINT(20) UNSIGNED NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY (`line_id`) REFERENCES `lines`(`id`),
FOREIGN KEY (`station_id`) REFERENCES `stations`(`id`)
);
Pantitlán tiene las lineas 1 5 9 y A. Cómo se hace en esos casos?
Hola estimada, por aca te comparto una alternativa usando Nested Queries.
Sin importar el ID de los registros, puedes usar el nombre de la linea y el nombre de la estacion como datos claves para formar las relaciones:
INSERTINTO`lines_stations`(line_id, station_id)VALUES((SELECT id FROM`lines`WHERE name ="Linea 1"),(SELECT id FROM`stations`WHERE name ="Pantitlan")),((SELECT id FROM`lines`WHERE name ="Linea 5"),(SELECT id FROM`stations`WHERE name ="Pantitlan")),((SELECT id FROM`lines`WHERE name ="Linea 9"),(SELECT id FROM`stations`WHERE name ="Pantitlan")),((SELECT id FROM`lines`WHERE name ="Linea A"),(SELECT id FROM`stations`WHERE name ="Pantitlan"));```
Y este seria el resultado:[](https://www.awesomescreenshot.com/image/34609054?key=f708091075004c6016fa8a0c8ce23162)
Es posible llenar los datos de todas las líneas sin necesidad de hacer tantos nested?.
Me refiero a anidar otro query dentro de los where del select a insertar, me quedó esa duda al momento de llenar los datos de manera dinámica cuando tengamos muchos registros
Sí, se puede, de hecho así lo hice originalmente antes de planear el curso, pero ya que estamos viendo Nested Queries me parecio mejor hacerlo así para aprovechar a mostrárselos. Pero si quieres puedes poner directamente los id, no hay problema :D
en este caso veo que lo hacen por cuestiones de práctica del uso de nested queries, pero claro es mas sencillo insertanto el id de la linea y el de la estación
Existe una mejor manera de llenar la tabla lines_stations con solo un Query.
.
Pero para lograr esto, hay que hacer cambios en la tabla de stations. Se tendría que agregar la columna line_id dentro de esta tabla de stations.
.
Yo lo hice de esa forma porque siempre cada estación va a pertenecer a una línea del metro. Y en caso de las estaciones con más de una línea, para eso nos va a ayudar la tabla pivot.
.
Despues de agregar este campo, hay que agregarle un valor a cada estación. Ese código lo tengo ya hecho en este archivo sql: https://github.com/irvingvjuarez/mariadb-course/blob/main/update/update-line-id.sql
.
Una vez que ya todas las estaciones tienen un valor en line_id, entonces ahora si podemos llenar de manera sencilla la tabla lines_stations con el siguiente query
USE cdmx_subway;INSERTINTOlines_stations(station_id, line_id)SELECT id, line_id
FROM stations;
Y listo, la tabla pivot se habrá llenado de valores de manera rápida y sencilla
Tengo suerte porque decidí hacer el proyecto con el metro de Buenos Aires que tiene 85 estaciones jeje
USE metro_cdmx;CREATE TABLE `lines_stations` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `line_id` BIGINT(20) UNSIGNED NOT NULL, `station_id` BIGINT(20) UNSIGNED NOT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), FOREIGN KEY (`line_id`) REFERENCES `lines` (`id`), FOREIGN KEY (`station_id`) REFERENCES `stations` (`id`))DEFAULT CHARSET=utf8mb4COLLATE=utf8mb4_unicode_ci
Cuando creo esta tabla desde la terminal, me arroja un ERROR 1005 (HY000) at line 3: Can't create table `metro_cdmx`.`lines_stations` (errno: 150 "Foreign key constraint is incorrectly formed"
alguien la ha salido error Foreign Key station_id?
USE metro_cdmx;CREATE TABLE `lines_stations` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `line_id` BIGINT(20) UNSIGNED NOT NULL, `station_id` BIGINT(20) UNSIGNED NOT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), FOREIGN KEY (`line_id`) REFERENCES `lines` (`id`), FOREIGN KEY (`station_id`) REFERENCES `stations` (`id`))DEFAULT CHARSET=utf8mb4COLLATE=utf8mb4_unicode_ci
Cuando creo esta tabla desde la terminal, me arroja un ERROR 1005 (HY000) at line 3: Can't create table `metro_cdmx`.`lines_stations` (errno: 150 "Foreign key constraint is incorrectly formed"
he revisado , y el error sale por el station_id ese station_id nolo tenemos creado en otra tabla como el line_id.Alguien ha tenido este probelma?
es necesario anadir un CONSTRAINT siempre?
Se puede hacer sin la necesidad de agregarlo?
CREATE TABLE `lines_station`( ID BIGINT(20) UNSIGNED AUTO_INCREMENT NOT NULL, LINE_ID BIGINT(20) UNSIGNED NOT NULL, STATION_ID BIGINT(20) UNSIGNED NOT NULL, CREATE_AT TIMESTAMP NOT NULL DEFAULT NOW(), UPDATE_AT TIMESTAMP NOT NULL DEFAULT NOW(), PRIMARY KEY (ID), CONSTRAINT fk_LINE_ID FOREIGN KEY (LINE_ID) REFERENCES `lines`(id), CONSTRAINT fk_STATION_ID FOREIGN KEY (STATION_ID) REFERENCES `stations`(id))DEFAULT CHARSET = utf8mb4COLLATE = utf8mb4_unicode_ci;
Este fue mi codigo para crear la tabla:
CREATE TABLE lines\_station( ID BIGINT(20) UNSIGNED AUTO_INCREMENT NOT NULL, LINE_ID BIGINT(20) UNSIGNED NOT NULL, STATION_ID BIGINT(20) UNSIGNED NOT NULL, CREATE_AT TIMESTAMP NOT NULL DEFAULT NOW(), UPDATE_AT TIMESTAMP NOT NULL DEFAULT NOW(), PRIMARY KEY (ID), CONSTRAINT fk_LINE_ID FOREIGN KEY (LINE_ID) REFERENCES lines(id), CONSTRAINT fk_STATION_ID FOREIGN KEY (STATION_ID) REFERENCES stations(id))DEFAULT CHARSET = utf8mb4COLLATE = utf8mb4_unicode_ci;
USE metro_cdmx;INSERTINTO`lines_stations`(line_id, stations_id)VALUES--Insertando primer Ferrería que pertenece a la línea 9((SELECT`lines`.`id`FROM`lines`WHERE`lines`.`name`="línea 9"),(SELECT`stations`.`id`FROM`stations`WHERE`stations`.`name`="Lázaro Cárdenas")),--InsertandoLázaro Cárdenas que pertenece a la línea 9((SELECT`lines`.`id`From`lines`WHERE`lines`.`name`="línea 9"),(SELECT`stations`.`id`FROM`stations`WHERE`stations`.`name`="Ferrería")),--InsertandoPantitlán que pertenece a la línea 1,5,9,A((SELECT`lines`.`id`FROM`lines`WHERE`lines`.`name`="línea 1"),(SELECT`stations`.`id`FROM`stations`WHERE`stations`.`name`="Pantitlán")),((SELECT`lines`.`id`FROM`lines`WHERE`lines`.`color`="Amarillo"),(SELECT`stations`.`id`FROM`stations`WHERE`stations`.`name`="Pantitlán")),((SELECT`lines`.`id`FROM`lines`WHERE`lines`.`color`="Morado"),(SELECT`stations`.`id`FROM`stations`WHERE`stations`.`name`="Pantitlán")),((SELECT`lines`.`id`FROM`lines`WHERE`lines`.`color`="Café"),(SELECT`stations`.`id`FROM`stations`WHERE`stations`.`name`="Pantitlán")),
<
USE metro_cdmx;
INSERT INTO lines\_stations(line_id, stations_id) VALUES--Insertando primer Ferrería que pertenece a la línea 9((SELECTlines.id FROM lines WHERE lines.name= "línea 9"), (SELECT stations. id FROM stations WHERE stations.name = "Lázaro Cárdenas")),--Insertando Lázaro Cárdenas que pertenece a la línea 9((SELECTlines.id From lines WHERE lines.name = "línea 9"),(SELECT stations.id FROM stations WHERE stations.name = "Ferrería")),--Insertando Pantitlán que pertenece a la línea 1, 5, 9, A((SELECT lines.id FROM lines WHERE lines.name = "línea 1"), (SELECT stations.id FROM stations WHERE stations.name = "Pantitlán")),((SELECT lines.id FROM lines WHERE lines.color = "Amarillo"), (SELECT stations.id FROM stations WHERE stations.name = "Pantitlán")),((SELECT lines.id FROM lines WHERE lines.color = "Morado"), (SELECT stations.id FROM stations WHERE stations.name = "Pantitlán")),((SELECT lines.id FROM lines WHERE lines.color = "Café"), (SELECT stations.id FROM stations WHERE stations.name = "Pantitlán")),