CREATE TABLE users ( user_id int NOT NULL AUTO_INCREMENT, username varchar(50) NOT NULL, password varchar(50) NOT NULL, phone varchar(50) NOT NULL, PRIMARY KEY (user_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE products ( product_id int NOT NULL AUTO_INCREMENT, product_name varchar(50) NOT NULL, product_description varchar(200) NOT NULL, product_price decimal(10,2) NOT NULL, PRIMARY KEY (product_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE shopping_cart ( user_id int NOT NULL, product_id int NOT NULL, quantity int NOT NULL, PRIMARY KEY (user_id,product_id), FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (product_id) REFERENCES products (product_id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, product_id INT, quantity INT, total DECIMAL(10, 2), order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(user_id), FOREIGN KEY (product_id) REFERENCES products(product_id) ); 实现下订单功能,并在下了订单之后,把商品从购物车里删了 sql语句
时间: 2024-03-20 11:42:51 浏览: 134
tushuguanlixitong.rar_图书管理系统 sql
以下是实现下订单功能,并在下了订单之后,把商品从购物车里删了的 SQL 语句:
```
-- 首先插入订单信息到 orders 表中
INSERT INTO orders (user_id, product_id, quantity, total)
SELECT user_id, product_id, quantity, product_price * quantity
FROM shopping_cart
JOIN products ON shopping_cart.product_id = products.product_id
WHERE user_id = [用户ID];
-- 然后删除购物车中对应的商品
DELETE FROM shopping_cart
WHERE user_id = [用户ID] AND product_id = [商品ID];
```
其中,将 `[用户ID]` 和 `[商品ID]` 替换为实际的用户 ID 和商品 ID 即可。另外,`orders` 表中的 `total` 字段为订单总价,根据购买数量和商品单价计算得出。
阅读全文