sql查询语句练习
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql查询语句练习相关的知识,希望对你有一定的参考价值。
#示例1:以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出年龄大于25岁的员工以及员工所在的部门
#SELECT department.name,employee.name FROM department INNER JOIN employee ON department.id=employee.dep_id WHERE employee.age >25;
#示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示
#SELECT * FROM department INNER JOIN employee ON department.id=employee.dep_id ORDER BY age DESC;
#查询平均年龄在25岁以上的部门名
#SELECT * FROM employee GROUP BY age HAVING AVG(age)>25 ;
#SELECT * FROM department WHERE id in (select dep_id from employee group by dep_id having avg(age) > 25)
#查看技术部员工姓名
#SELECT name FROM employee WHERE dep_id in (SELECT id FROM department WHERE name=‘技术‘)
#查看不足1人的部门名
#SELECT name FROM department WHERE id in (SELECT dep_id FROM employee GROUP BY dep_id HAVING COUNT(dep_id )<=1)
#查询大于所有人平均年龄的员工名与年龄
#(SELECT avg(age) FROM employee GROUP BY dep_id HAVING AVG(age))
#SELECT name,age FROM employee WHERE age > (SELECT AVG(age) FROM employee)
#查询大于部门内平均年龄的员工名、年龄
#SELECT dep_id,avg(age) age FROM employee GROUP BY dep_id
#SELECT d.* FROM department d LEFT JOIN employee e ON d.id=e.dep_id
#LEFT JOIN (SELECT dep_id,avg(age) age FROM employee GROUP BY dep_id) a ON d.id=a.dep_id
#WHERE d.age>a.age
#SELECT employee.name,employee.age FROM employee INNER JOIN
#(SELECT dep_id,avg(age) age FROM employee GROUP BY dep_id) a ON employee.dep_id=a.dep_id
#WHERE employee.age>a.age
#department表中存在dept_id=203,Ture,内部条件为真,则执行外部语句
#SELECT * FROM department WHERE EXISTS (select id from department where id=200)
#练习:查询每个部门最新入职的那位员工
#SELECT MAX(hire_date) hire_date,depart_id FROM company GROUP BY depart_id
#SELECT company.name,company.hire_date FROM company INNER JOIN (SELECT MAX(hire_date) hire_date,depart_id FROM company GROUP BY depart_id) a
#ON company.depart_id=a.depart_id
#WHERE company.hire_date=a.hire_date
#SELECT * FROM table1
#SELECT * from table2
#查询来自杭州,并且订单数少于2的客户。
#SELECT * FROM table1 LEFT JOIN table2 ON table1.customer_id=table2.customer_id
/*
SELECT a.customer_id, COUNT(b.order_id) as total_orders
FROM table1 AS a
LEFT JOIN table2 AS b
ON a.customer_id = b.customer_id
WHERE a.city = ‘hangzhou‘
GROUP BY a.customer_id
HAVING count(b.order_id) < 2
ORDER BY total_orders DESC;
*/
以上是关于sql查询语句练习的主要内容,如果未能解决你的问题,请参考以下文章