SQL
This commit is contained in:
parent
2f48dbdb45
commit
06fc0ee834
114
Practicas/Practicas_SQL/codigo/INTRO_SQL_comandos_DML_3_JOIN.sql
Normal file
114
Practicas/Practicas_SQL/codigo/INTRO_SQL_comandos_DML_3_JOIN.sql
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
|
||||
--COMBINAR DATOS DE DISTINTAS TABLAS
|
||||
--JOIN se utilizan para combinar filas de dos o más tablas en función de una condición relacionada.
|
||||
--empleados
|
||||
| id_empleado | nombre | id_departamento |
|
||||
|-------------|----------|-----------------|
|
||||
| 1 | Juan | 1 |
|
||||
| 2 | María | 1 |
|
||||
| 3 | Pedro | 2 |
|
||||
| 4 | Ana | 3 |
|
||||
|
||||
--departamentos
|
||||
| id_departamento | nombre |
|
||||
|-----------------|-------------|
|
||||
| 1 | Ventas |
|
||||
| 2 | Recursos Hum|
|
||||
| 4 | Taller |
|
||||
|
||||
|
||||
******************************************
|
||||
--INNER JOIN solo las filas que tienen un valor común en ambas tablas(solo JOIN)
|
||||
--ON condicion de unión
|
||||
SELECT e.*, d.nombre AS nombre_departamento
|
||||
FROM empleados e
|
||||
INNER JOIN departamentos d ON e.id_departamento = d.id_departamento;
|
||||
| id_empleado | nombre | id_departamento | nombre_departamento |
|
||||
|-------------|--------|-----------------|--------------------|
|
||||
| 1 | Juan | 1 | Ventas |
|
||||
| 2 | María | 1 | Ventas |
|
||||
| 3 | Pedro | 2 | Recursos Hum |
|
||||
|
||||
--**** Tienda
|
||||
SELECT * FROM clientes
|
||||
JOIN usuarios
|
||||
ON clientes.cliente_id = usuarios.cliente_id;
|
||||
|
||||
--Tres tablas (orden de JOIN)
|
||||
SELECT *
|
||||
FROM clientes
|
||||
INNER JOIN pedidos ON clientes.cliente_id = pedidos.cliente_id
|
||||
INNER JOIN detalles_pedido ON pedidos.pedido_id = detalles_pedido.pedido_id;
|
||||
-- Devuelve los pedidos que tienen tanto información del cliente como detalles del pedido.
|
||||
|
||||
--Agrupando para obtener el total por pedido
|
||||
SELECT clientes.nombre, pedidos.pedido_id, SUM(detalles_pedido.cantidad * detalles_pedido.precio_unitario) AS total
|
||||
FROM clientes
|
||||
INNER JOIN pedidos ON clientes.cliente_id = pedidos.cliente_id
|
||||
INNER JOIN detalles_pedido ON pedidos.pedido_id = detalles_pedido.pedido_id
|
||||
GROUP BY pedidos.pedido_id;
|
||||
|
||||
|
||||
************************************
|
||||
--LEFT JOIN (o LEFT OUTER JOIN): Devuelve todas las filas de la tabla izquierda (primera tabla mencionada) y las filas coincidentes de la tabla derecha (segunda tabla mencionada). Si no hay coincidencias en la tabla derecha, se devuelven NULL en las columnas correspondientes.
|
||||
SELECT e.*, d.nombre AS nombre_departamento
|
||||
FROM empleados e
|
||||
LEFT JOIN departamentos d ON e.id_departamento = d.id_departamento;
|
||||
| id_empleado | nombre | id_departamento | nombre_departamento |
|
||||
|-------------|--------|-----------------|--------------------|
|
||||
| 1 | Juan | 1 | Ventas |
|
||||
| 2 | María | 1 | Ventas |
|
||||
| 3 | Pedro | 2 | Recursos Hum |
|
||||
| 4 | Ana | 3 | null |
|
||||
|
||||
--**** Tienda
|
||||
SELECT *
|
||||
FROM clientes
|
||||
LEFT JOIN pedidos ON clientes.cliente_id = pedidos.cliente_id
|
||||
LEFT JOIN detalles_pedido ON pedidos.pedido_id = detalles_pedido.pedido_id;
|
||||
--Devolverá todos los clientes, incluso si no tienen ningún pedido registrado.
|
||||
|
||||
|
||||
***********************************
|
||||
--RIGHT JOIN (o RIGHT OUTER JOIN): Devuelve todas las filas de la tabla derecha (segunda tabla mencionada) y las filas coincidentes de la tabla izquierda (primera tabla mencionada). Si no hay coincidencias en la tabla izquierda, se devuelven NULL en las columnas correspondientes.
|
||||
SELECT e.*, d.nombre AS nombre_departamento
|
||||
FROM empleados e
|
||||
RIGHT JOIN departamentos d ON e.id_departamento = d.id_departamento;
|
||||
| id_empleado | nombre | id_departamento | nombre_departamento |
|
||||
|-------------|--------|-----------------|--------------------|
|
||||
| 1 | Juan | 1 | Ventas |
|
||||
| 2 | María | 1 | Ventas |
|
||||
| 3 | Pedro | 2 | Recursos Hum |
|
||||
|null | null | 4 | Taller |
|
||||
|
||||
--**** Tienda
|
||||
SELECT *
|
||||
FROM clientes
|
||||
RIGHT JOIN pedidos ON clientes.cliente_id = pedidos.cliente_id
|
||||
--Devolverá todos los pedidos, incluso si no están asociados con ningún cliente.
|
||||
|
||||
|
||||
**************************************
|
||||
--FULL JOIN (No soportado en MySQL): Devuelve todas las filas de ambas tablas, combinando las filas de ambas tablas donde sea posible. Si no hay coincidencias, se devuelven NULL en las columnas correspondientes.
|
||||
SELECT e.*, d.nombre AS nombre_departamento
|
||||
FROM empleados e
|
||||
FULL JOIN departamentos d ON e.id_departamento = d.id_departamento;
|
||||
| id_empleado | nombre | id_departamento | nombre_departamento |
|
||||
|-------------|--------|-----------------|--------------------|
|
||||
| 1 | Juan | 1 | Ventas |
|
||||
| 2 | María | 1 | Ventas |
|
||||
| 3 | Pedro | 2 | Recursos Hum |
|
||||
| 4 | Ana | 3 | null |
|
||||
|null | null | 4 | Taller |
|
||||
|
||||
|
||||
--**** Tienda
|
||||
SELECT *
|
||||
FROM clientes
|
||||
LEFT JOIN pedidos ON clientes.cliente_id = pedidos.cliente_id
|
||||
LEFT JOIN detalles_pedido ON pedidos.pedido_id = detalles_pedido.pedido_id
|
||||
UNION
|
||||
SELECT *
|
||||
FROM clientes
|
||||
RIGHT JOIN pedidos ON clientes.cliente_id = pedidos.cliente_id
|
||||
RIGHT JOIN detalles_pedido ON pedidos.pedido_id = detalles_pedido.pedido_id;
|
||||
89
Practicas/Practicas_SQL/ejercicios/tienda/crud_clientes.php
Normal file
89
Practicas/Practicas_SQL/ejercicios/tienda/crud_clientes.php
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
$variable = 'texto boton';
|
||||
|
||||
$clientes = getClientes();
|
||||
|
||||
function conectBD()
|
||||
{
|
||||
$nombre_servidor = "localhost";
|
||||
$nombre_usuario = "root";
|
||||
$contraseña = "Logomark8";
|
||||
$nombre_base_datos = "tienda";
|
||||
mysqli_report(MYSQLI_REPORT_OFF);
|
||||
$conexion = mysqli_connect($nombre_servidor, $nombre_usuario, $contraseña, $nombre_base_datos);
|
||||
if (!$conexion) {
|
||||
exit("Error de conexión: " . mysqli_connect_error());
|
||||
}
|
||||
return $conexion;
|
||||
}
|
||||
function getClientes()
|
||||
{
|
||||
$conexion = conectBD();
|
||||
$consulta_sql = "SELECT c.*, u.* FROM usuarios u LEFT JOIN clientes c ON u.cliente_id = c.cliente_id;";
|
||||
$resultado = mysqli_query($conexion, $consulta_sql);
|
||||
if (!$resultado) {
|
||||
exit("Error al ejecutar la consulta: " . mysqli_error($conexion));
|
||||
}
|
||||
$clientes = mysqli_fetch_all($resultado, MYSQLI_ASSOC);
|
||||
mysqli_free_result($resultado);
|
||||
mysqli_close($conexion);
|
||||
return $clientes;
|
||||
}
|
||||
?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="estilo.css">
|
||||
<title>Crud Clientes</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<form action="">
|
||||
<table style="width:100%;">
|
||||
<tr>
|
||||
<th>Nombre</th>
|
||||
<th>Email</th>
|
||||
<th>Direccion</th>
|
||||
<th>UserName</th>
|
||||
<th>Password</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input type="text" name="nombre" id=""></td>
|
||||
<td><input type="text" name="email" id=""></td>
|
||||
<td><input type="text" name="direccion" id=""></td>
|
||||
<td><input type="text" name="username" id=""></td>
|
||||
<td><input type="password" name="password" id=""></td>
|
||||
<td><input style="margin-bottom: 20px; padding:11px 20px;" type="submit" value="<?= $variable ?>"></td>
|
||||
</tr>
|
||||
</table>
|
||||
</form>
|
||||
|
||||
<table style="width:100%;">
|
||||
<?php if (isset($clientes) && !empty($clientes)) : ?>
|
||||
<?php foreach ($clientes as $cliente) : ?>
|
||||
<tr>
|
||||
<td><?= $cliente['nombre'] ?></td>
|
||||
<td><?= $cliente['correo_electronico'] ?></td>
|
||||
<td><?= $cliente['direccion'] ?></td>
|
||||
<td><?= $cliente['nombre_usuario'] ?></td>
|
||||
<td><?= $cliente['contraseña'] ?></td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php else : ?>
|
||||
<tr>
|
||||
<td colspan="6" style="text-align:center;">
|
||||
<p style="font-size: 3rem;">No hay clientes</p>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endif; ?>
|
||||
</table>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,13 +1,12 @@
|
|||
<?php
|
||||
// Comprobamos si existe la sesión
|
||||
session_start();
|
||||
if (!isset($_SESSION['cliente_id'])) {
|
||||
// En caso contrario devolvemos a la página login.php
|
||||
header('Location: login.php');
|
||||
die();
|
||||
}
|
||||
|
||||
$cliente_id = $_SESSION['cliente_id'];
|
||||
|
||||
$nombre_servidor = "localhost";
|
||||
$nombre_usuario = "root";
|
||||
$contraseña = "Logomark8";
|
||||
|
|
@ -29,8 +28,8 @@ $productos = mysqli_fetch_all($resultado, MYSQLI_ASSOC);
|
|||
|
||||
mysqli_free_result($resultado);
|
||||
mysqli_close($conexion);
|
||||
?>
|
||||
|
||||
?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
|
@ -44,32 +43,84 @@ mysqli_close($conexion);
|
|||
|
||||
<body>
|
||||
<h2>Registrar Pedido</h2>
|
||||
<form action="" method="post">
|
||||
<table>
|
||||
<tr>
|
||||
<th>Descripcion</th>
|
||||
<th>Precio</th>
|
||||
<th>Cantidad</th>
|
||||
</tr>
|
||||
<?php
|
||||
foreach ($productos as $producto) {
|
||||
echo "<tr>";
|
||||
echo "<td>$producto[nombre] </td> <td>$producto[precio] € </td>";
|
||||
echo "<td hidden> <input type='number' id='producto_id' name='producto_id[]' value=$producto[producto_id]></td>";
|
||||
echo "<td hidden> <input type='number' id='precio' name='precio[]' value=$producto[precio]></td>";
|
||||
echo "<td> <input type='number' id='cantidad' name='cantidad[]' value=0></td>";
|
||||
echo "</tr>";
|
||||
}
|
||||
?>
|
||||
</table>
|
||||
<br>
|
||||
<input type="submit" value="Registrar Pedido">
|
||||
</form>
|
||||
|
||||
<div style="display: flex; flex-direction: row; gap:1rem;">
|
||||
<form style="display: inline-block; width: 100%;" action="" method="post">
|
||||
<table>
|
||||
<tr>
|
||||
<th>Descripcion</th>
|
||||
<th>Precio</th>
|
||||
<th>Cantidad</th>
|
||||
</tr>
|
||||
<?php
|
||||
foreach ($productos as $producto) {
|
||||
echo "<tr>";
|
||||
echo "<td>$producto[nombre] </td> <td style='text-align: right;'>$producto[precio] € </td>";
|
||||
echo "<td hidden> <input type='text' id='producto_nombre' name='producto_nombre[]'value='$producto[nombre]'></td>";
|
||||
echo "<td hidden> <input type='number' id='producto_id' name='producto_id[]'value=$producto[producto_id]></td>";
|
||||
echo "<td hidden> <input type='number' id='precio' name='precio[]' value=$producto[precio]></td>";
|
||||
echo "<td> <input style='text-align: right;' type='number' id='cantidad' name='cantidad[]' value=0 min='0'></td>";
|
||||
echo "</tr>";
|
||||
}
|
||||
?>
|
||||
</table>
|
||||
<br>
|
||||
<input type="submit" name="registrar" value="Registrar Pedido">
|
||||
</form>
|
||||
|
||||
<?php muestraPedido() ?>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
</body>
|
||||
|
||||
<?php
|
||||
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||
function muestraPedido()
|
||||
{
|
||||
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['registrar']) && (array_sum($_POST['cantidad']) !== 0)) {
|
||||
$lineas_pedido = array();
|
||||
$total_pedido = 0;
|
||||
foreach (array_keys($_POST['producto_id']) as $index) {
|
||||
if ($_POST['cantidad'][$index] > 0) {
|
||||
$lineas_pedido[] = array(
|
||||
'nombre' => $_POST['producto_nombre'][$index],
|
||||
'producto_id' => intval($_POST['producto_id'][$index]),
|
||||
'cantidad' => intval($_POST['cantidad'][$index]),
|
||||
'precio' => floatval($_POST['precio'][$index]),
|
||||
'total_linea' => $_POST['cantidad'][$index] * $_POST['precio'][$index]
|
||||
);
|
||||
$total_pedido += $_POST['cantidad'][$index] * $_POST['precio'][$index];
|
||||
}
|
||||
}
|
||||
echo "
|
||||
<form style='display: inline-block; width: 100%;' action='' method='post'>
|
||||
<table style='width:100%'>
|
||||
<tr>
|
||||
<th>Id</th>
|
||||
<th>Descripcion</th>
|
||||
<th>Cantidad</th>
|
||||
<th>Precio Uni.</th>
|
||||
<th>Total linea</th>
|
||||
</tr>";
|
||||
foreach ($lineas_pedido as $linea) {
|
||||
echo "<tr>";
|
||||
echo "<td>$linea[producto_id]</td><td>$linea[nombre]</td> <td style='text-align: right;'>$linea[cantidad]</td> <td style='text-align: right;'>$linea[precio] €</td> <td style='text-align: right;'>$linea[total_linea] €</td>";
|
||||
echo "<td hidden> <input type='number' id='producto_id' name='producto_id[]'value=$linea[producto_id]></td>";
|
||||
echo "<td hidden> <input type='number' id='precio' name='precio[]' value=$linea[precio]></td>";
|
||||
echo "<td hidden> <input type='number' id='cantidad' name='cantidad[]' value=$linea[cantidad]></td>";
|
||||
echo "</tr>";
|
||||
}
|
||||
echo "<tr><td colspan=3></td><td style='text-align: right;'>Total: </td><td style='text-align: right;'>$total_pedido €</td></tr>";
|
||||
echo "</table>
|
||||
<br>
|
||||
<input type='submit' name='confirmar' value='Confirmar Pedido'>
|
||||
</form>
|
||||
";
|
||||
}
|
||||
}
|
||||
|
||||
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['confirmar'])) {
|
||||
$lineas_pedido = array();
|
||||
$total_pedido = 0;
|
||||
|
||||
|
|
@ -90,12 +141,30 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
|||
$nombre_usuario = "root";
|
||||
$contraseña = "Logomark8";
|
||||
$nombre_base_datos = "tienda";
|
||||
|
||||
mysqli_report(MYSQLI_REPORT_OFF);
|
||||
$conexion = mysqli_connect($nombre_servidor, $nombre_usuario, $contraseña, $nombre_base_datos);
|
||||
if (!$conexion) {
|
||||
exit("Error de conexión: " . mysqli_connect_error());
|
||||
}
|
||||
|
||||
$estado_pedido = "pendiente";
|
||||
$consulta_pedido = "INSERT INTO pedidos (cliente_id, fecha, estado, total) VALUES ('$cliente_id', NOW(), '$estado_pedido','$total_pedido')";
|
||||
if (!mysqli_query($conexion, $consulta_pedido)) {
|
||||
exit("Error al registrar el pedido: " . mysqli_error($conexion));
|
||||
} else {
|
||||
$pedido_id = mysqli_insert_id($conexion);
|
||||
foreach ($lineas_pedido as $linea) {
|
||||
$producto_id = $linea['producto_id'];
|
||||
$cantidad = $linea['cantidad'];
|
||||
$precio_unitario = $linea['precio'];
|
||||
$consulta_detalles = "INSERT INTO detalles_pedido (pedido_id, producto_id, cantidad, precio_unitario) VALUES ('$pedido_id', '$producto_id', '$cantidad', '$precio_unitario')";
|
||||
if (!mysqli_query($conexion, $consulta_detalles)) {
|
||||
exit("Error al registrar los detalles del pedido: " . mysqli_error($conexion));
|
||||
}
|
||||
}
|
||||
echo "<p>El pedido ha sido registrado correctamente</p>";
|
||||
}
|
||||
mysqli_close($conexion);
|
||||
}
|
||||
?>
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user