Working with two tables - MySQL

 Let’s create two tables connected by a foreign key and then explore some sample queries.


First, we’ll create two tables: Customers and Products. The Customers table will have an id (as the primary key), name, and age. The Products table will have a customer_id (as a foreign key referencing the id column in the Customers table), and a name.

CREATE TABLE Customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    age INT NOT NULL
);

CREATE TABLE Products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT,
    name VARCHAR(255) NOT NULL,
    FOREIGN KEY (customer_id) REFERENCES Customers(id)
);


In this example, the customer_id column in the Products table references the id column in the Customers table. This establishes a relationship between the two tables.

INSERT INTO Customers (name, age) VALUES
    ('John Doe', 30),
    ('Jane Smith', 25),
    ('Mike Johnson', 35),
    ('Alice Brown', 28);

INSERT INTO Products (customer_id, name) VALUES
    (1, 'Product A'),
    (1, 'Product B'),
    (2, 'Product C'),
    (3, 'Product D'),
    (4, 'Product E');

1.Retrieve all customers:
SELECT * FROM Customers;

2.Retrieve all products:
SELECT * FROM Products;

3.Retrieve all customers and their products:
SELECT c.name AS customer_name, p.name AS product_name
FROM Customers c
JOIN Products p ON c.id = p.customer_id;

4.Count the number of products for each customer:
SELECT c.name AS customer_name, COUNT(p.id) AS num_products
FROM Customers c
LEFT JOIN Products p ON c.id = p.customer_id
GROUP BY c.id, c.name;

5.Find customers who have not purchased any products:
SELECT c.name AS customer_name
FROM Customers c
LEFT JOIN Products p ON c.id = p.customer_id
WHERE p.id IS NULL;

6.Find all products for a specific customer (e.g., customer_id = 1):
SELECT p.name AS product_name
FROM Products p
WHERE p.customer_id = 1;

7.Get customer details along with the count of products they have purchased:
SELECT c.id, c.name, c.age, COUNT(p.id) AS product_count
FROM Customers c
LEFT JOIN Products p ON c.id = p.customer_id
GROUP BY c.id, c.name, c.age;

8.List all customers who are older than 30 and their products:
SELECT c.name AS customer_name, p.name AS product_name
FROM Customers c
JOIN Products p ON c.id = p.customer_id
WHERE c.age > 30;

9.List all customers who are older than 30 and their products:
SELECT c.name AS customer_name, p.name AS product_name
FROM Customers c
JOIN Products p ON c.id = p.customer_id
WHERE c.age > 30;

10.Find the average age of customers who purchased products
SELECT AVG(age) AS avg_customer_age
FROM Customers
WHERE id IN (SELECT DISTINCT customer_id FROM Products);

11.Update a customer's name
UPDATE Customers
SET name = 'Jonathan Doe'
WHERE id = 1;

12.Delete a product by its id:
DELETE FROM Products
WHERE id = 2;


Comments

Popular posts from this blog

KTU DBMS LAB CSL 333 BTech S5 - Dr Binu V P

Procedures in PL/SQL

Cursors in PL/SQL