📅  最后修改于: 2023-12-03 14:47:38.180000             🧑  作者: Mango
SQL注释是SQL代码中的一种特殊语法,用于提高代码的可读性和可维护性。注释可以用于描述代码的功能、作者、修改日期等信息,还可以用于暂时禁用某段代码或调试问题。
SQL注释可以分为两种类型:
--
开头,后面跟着注释内容,注释内容在此行结束。/*
开头,以*/
结尾,注释内容可以跨行。-- 单行注释
SELECT *
FROM table1;
/*
多行注释
*/
SELECT *
FROM table2;
-- SQL注释常见用例
/* 查找用户表中最近一年注册的用户 */
SELECT *
FROM user
WHERE register_time > DATE_SUB(NOW(), INTERVAL 1 YEAR)
ORDER BY register_time;
/* 查询用户购物车商品数量,此处使用连接查询 */
SELECT u.username, COUNT(c.goods_id) AS cart_count
FROM users u
LEFT JOIN cart c ON u.user_id = c.user_id
GROUP BY u.user_id;
/*
说明:此处暂时使用LIMIT 0来禁用SQL语句,以便调试。
*/
SELECT *
FROM users
LIMIT 0;
/* 更新用户密码,记录修改日志 */
UPDATE users
SET password = 'xxxxxx'
WHERE user_id = 1;
/* 删除用户数据及相关数据,记录删除记录 */
DELETE FROM users
WHERE user_id = 1;
/* 复杂查询:查找最近6个月销售量TOP10的商品 */
SELECT p.product_name, SUM(o.quantity) AS total_sales
FROM product p
INNER JOIN order_detail o ON p.product_id = o.product_id
INNER JOIN orders od ON o.order_no = od.order_no
WHERE od.order_time BETWEEN DATE_SUB(NOW(), INTERVAL 6 MONTH) AND NOW()
GROUP BY p.product_id
ORDER BY total_sales DESC
LIMIT 10;
-- SQL注释示例(注释格式统一)
/*
说明:查找最近6个月销售量TOP10的商品。
*/
SELECT p.product_name, SUM(o.quantity) AS total_sales
FROM product p
INNER JOIN order_detail o ON p.product_id = o.product_id
INNER JOIN orders od ON o.order_no = od.order_no
WHERE od.order_time BETWEEN DATE_SUB(NOW(), INTERVAL 6 MONTH) AND NOW()
GROUP BY p.product_id
ORDER BY total_sales DESC
LIMIT 10;
/*
说明:此处用于备份用户数据,备份数据表为user_backup。
*/
INSERT INTO user_backup
SELECT * FROM user;