?USER用户表:
USER_LOGIN_LOG用户登录表:?
1、单表查询:?
-- 1.查询用户表用性别为女(sex 0 为未知,1男,2女)的用户的username,password,sex,status
SELECT username,`password`,sex,`status` FROM `user` WHERE sex=2;
-- 2.查询金额大于等于100 的用户的username,nickname,sex,status
SELECT username,nickname,sex,`status` FROM `user`WHERE money>=100;
-- 3.查询性别为男或者性别未知(0,1)用户的username,nickname,status
SELECT username,nickname,`status` FROM `user`WHERE sex=1 OR sex=0;
-- 4.查询昵称中有 "白" 的用户
SELECT * FROM `user` WHERE nickname LIKE '%白%';
-- 5.查询没有填写电话号码(没有填写电话号码为NULL)的用户
SELECT * FROM `user` WHERE phone IS NULL;
-- 6.查询电话号码中 前三位133 后4位为7204的用户
SELECT * FROM `user` WHERE phone LIKE '133____7204';
-- 7.查询没有填写生日的用户
SELECT * FROM `user` WHERE birthday IS NULL;
-- 8.根据性别(sex)分组统计用户金额,平均值,最大值,总和,最小值并用AS 指定列的别名
SELECT AVG(money) AS avg_money,MAX(money) AS max_money,SUM(money) as sum_money,MIN(money) AS min_money,sex FROM `user` GROUP BY sex;
-- 9.每页3条数据,查询第2页的数据
SELECT * FROM `user` LIMIT 3,3;
SELECT * FROM `user_login_log` LIMIT 3,3;
2、多表查询
-- 根据多表查询user,user_login_log
-- 10.查询登录过系统的用户(即user_login_log表中存在),IN,EXISTS,JOIN 都可以
SELECT DISTINCT u.id,u.* FROM `user` AS u RIGHT JOIN user_login_log AS ul ON u.id=ul.user_id WHERE u.id IS NOT NULL;
SELECT * FROM `user` AS u WHERE u.id IN (SELECT user_id FROM user_login_log);
SELECT * FROM `user` AS u WHERE EXISTS (SELECT * FROM user_login_log WHERE u.id = user_login_log.user_id);
-- 12. 查询没有登录过系统的用户(即user_login_log表中不存在),IN,EXISTS,JOIN 都可以
SELECT * FROM `user` AS u WHERE u.id NOT IN (SELECT user_id FROM user_login_log);
SELECT DISTINCT u.id,u.* FROM `user` AS u LEFT JOIN user_login_log AS ul ON u.id=ul.user_id WHERE ul.user_id IS NULL;
SELECT * FROM `user` AS u WHERE NOT EXISTS (SELECT * FROM user_login_log WHERE u.id = user_login_log.user_id);
|