下面是一些 MySQL 数据库中的数据查询操作示例,包括单表查询和多表查询,以及相应的示例数据表。
单表查询:
假设我们有一个名为 products
的表,用于存储产品信息:
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(255),
category VARCHAR(50),
price DECIMAL(10, 2)
);
INSERT INTO products (product_id, product_name, category, price)
VALUES
(1, 'Laptop', 'Electronics', 799.99),
(2, 'Smartphone', 'Electronics', 499.99),
(3, 'Desk Chair', 'Furniture', 149.99),
(4, 'Coffee Table', 'Furniture', 199.99),
(5, 'Tennis Racket', 'Sports', 79.99);
-
查询表中的所有数据:
SELECT * FROM products;
-
查询特定列的所有数据:
SELECT product_name, price FROM products;
-
查询具有特定条件的数据:
SELECT * FROM products WHERE category = 'Electronics';
-
查询不同的行:
SELECT DISTINCT category FROM products;
-
对结果进行排序:
SELECT * FROM products ORDER BY price DESC;
多表查询:
假设我们有两个表:orders
表和 order_items
表,以及一个关联它们的 order_id
列。
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_name VARCHAR(255),
order_date DATE
);
INSERT INTO orders (order_id, customer_name, order_date)
VALUES
(101, 'John Doe', '2023-01-15'),
(102, 'Jane Smith', '2023-02-20'),
(103, 'Bob Johnson', '2023-03-10');
CREATE TABLE order_items (
order_item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT
);
INSERT INTO order_items (order_item_id, order_id, product_id, quantity)
VALUES
(1, 101, 1, 2),
(2, 102, 2, 1),
(3, 103, 4, 3);
-
查询所有订单及其订单项信息:
SELECT orders.order_id, orders.customer_name, orders.order_date, order_items.product_id, order_items.quantity FROM orders INNER JOIN order_items ON orders.order_id = order_items.order_id;
-
查询特定客户的订单信息:
SELECT orders.order_id, orders.customer_name, orders.order_date, order_items.product_id, order_items.quantity FROM orders INNER JOIN order_items ON orders.order_id = order_items.order_id WHERE orders.customer_name = 'John Doe';
-
查询每个订单的总价:
SELECT orders.order_id, SUM(products.price * order_items.quantity) AS total_price FROM orders INNER JOIN order_items ON orders.order_id = order_items.order_id INNER JOIN products ON order_items.product_id = products.product_id GROUP BY orders.order_id;
这些示例提供了带有详细表和数据的单表查询和多表查询操作示例。您可以根据这些示例根据自己的需求进行自定义修改。确保将实际的表名和列名替换为您的数据库中的实际信息。
标签:product,12,orders,items,查询,products,mysql,order,id From: https://www.cnblogs.com/itlaoboy/p/17673920.html