MySQL作为世界上最流行的开源关系型数据库管理系统,因其高性能、高可靠性和易用性而被广泛应用于各种规模的应用程序中。无论是个人网站、企业级应用还是云计算环境,MySQL都能提供稳定可靠的数据存储和管理解决方案。
例如简单的电商销售数据分析
表名为 sales_data,包含字段id,category, amount, region
SELECT
region, category, SUM(amount) AS sales, COUNT(id) AS count
FROM
data
GROUP BY
region,
category
ORDER BY
region,
sales DESC;
又像是简化为关键词匹配
表名为 social_media_comments,包含字段 comment_id, comment_text
SELECT
comment_id,
comment_text,
CASE
WHEN comment_text LIKE '%太棒了%' OR comment_text LIKE '%喜欢%' THEN '积极'
WHEN comment_text LIKE '%失望%' OR comment_text LIKE '%不好用%' THEN '消极'
ELSE '中性'
END AS sentiment
FROM
social_media_comments;
网站用户行为分析
表名为 website_logs,包含字段 user_id, page, visit_time
SELECT
user_id,
COUNT(page) AS page_count,
SUM(visit_time) AS total_time,
SUM(visit_time) / COUNT(page) AS avg_time
FROM
website_logs
GROUP BY
user_id;
简化为条件判断
表名为 patient_records,包含字段 patient_id, age, blood_pressure, blood_sugar, has_disease
SELECT
patient_id,
age,
blood_pressure,
blood_sugar,
CASE
WHEN age > 30 AND blood_pressure > 130 AND blood_sugar > 90 THEN 1
ELSE 0
END AS predicted_disease
FROM
patient_records;
消耗分析
-- 假设表名为 energy_consumption,包含字段 device_name, consumption
SELECT
device_name,
consumption
FROM
energy_consumption;
较为复杂的订单分析
客户表
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100),
country VARCHAR(50)
);
产品表
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
price DECIMAL(10, 2)
);
订单表
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
product_id INT,
order_date DATE,
quantity INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
或许可以再加一点
此 SQL 用于查询每个订单中,总订单金额最高的客户及其所购买的产品信息
计算每个客户的总订单金额
WITH customer_total AS (
SELECT
c.customer_id,
c.customer_name,
c.country,
SUM(p.price * o.quantity) AS total_amount
FROM
customers c
JOIN
orders o ON c.customer_id = o.customer_id
JOIN
products p ON o.product_id = p.product_id
GROUP BY
c.customer_id, c.customer_name, c.country
),
找出总订单金额最高的客户
top_customer_per_country AS (
SELECT
country,
MAX(total_amount) AS max_amount
FROM
customer_total
GROUP BY
country
)
获取中总订单金额最高的客户及其所购买的产品信息
SELECT
ct.customer_id,
ct.customer_name,
ct.country,
ct.total_amount,
p.product_name,
o.quantity,
o.order_date
FROM
customer_total ct
JOIN
top_customer_per_country tcpc ON ct.country = tcpc.country AND ct.total_amount = tcpc.max_amount
JOIN
orders o ON ct.customer_id = o.customer_id
JOIN
products p ON o.product_id = p.product_id
ORDER BY
ct.country, ct.total_amount DESC;
通过以上简单的MySQL应用示例,我们可以看到MySQL作为一款轻量级但功能强大的数据库管理系统。