5、基础查询
-- 1、查询用户信息仅显示姓名与手机号
SELECT username as '姓名',phone as '手机号' from users;
-- 2、模糊查询和explain语句
alter table stocks add index stock_name_index(stock_name);
explain SELECT * from stocks where stock_name like '%东吴证券%';
-- 3、统计用户订单信息,查询所有用户的下单数量,并进行倒序排列。
SELECT user_id, COUNT(order_id) as '订单数量' from orders group by user_id order by count(order_id) desc;
6、复杂查询
-- 1. 查询用户的基本信息
SELECT * FROM users;
-- 2. 查看订单中下单最多的股票产品对应的类别
SELECT stock_name, COUNT(*) AS order_count
FROM orders o
JOIN stocks s ON o.stock_id = s.stock_id
GROUP BY stock_name
ORDER BY order_count DESC
LIMIT 1;
-- 3. 查询下单股票数量最多的用户,并查询用户的全部信息与当前股票剩余库存
SELECT u.*, p.quantity AS remaining_stock_quantity
FROM users u
JOIN (
SELECT user_id, SUM(quantity) AS total_quantity
FROM transactions
GROUP BY user_id
ORDER BY total_quantity DESC
LIMIT 1
) t ON u.user_id = t.user_id
JOIN portfolios p ON u.user_id = p.user_id;