SQL常用知识点

1.查询去重

SELECT DISTINCT department_id FROM employees;

2.排序

SELECT column1, column2, ...
FROM table
ORDER BY column1 [ASC | DESC];
SELECT column1, column2, ...
FROM table
ORDER BY column1 ASC, column2 DESC, ...;

3.限定结果数量

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 10;

4.分页查询(offset表示排序后忽略最前面的10条数据)

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 10 OFFSET 10;

5.分组查询

  聚合函数

  • AVG - 计算一组值的平均值。
  • COUNT - 统计一组值的数量。
  • MAX - 计算一组值的最大值。
  • MIN - 计算一组值的最小值。
  • SUM - 计算一组值的和值。
  • STRING_AGG - 连接一组字符串。
SELECT department_id,
 AVG(salary),
 COUNT(*),
 MAX(salary),
 MIN(salary),
 SUM(salary)
FROM employees
GROUP BY department_id
ORDER BY department_id;

6.having 对分组后的数据进行过滤,如果没有分组则认为当前数据为一个组。

  select ManagerId as Id
  from Employee
  group by ManagerId
  having count(Id) >= 5

7.join多表连接查询

  inner join:只显示连接条件不为空的数据,如果on后面的连接数据为空 则查询不到。

select a.name, b.name
from
    aaa as a
inner join
    bbb as b
on
    a.id = b.id
where
    a.age = 18 and b.add = 'qwe'

  left join:以表aaa为主表,会把连接之后aaa表中的数据全部显示出来,即便bbb表中的没有与之对应的id 也会查询出来。

select a.name, b.name
from
    aaa as a
left join
    bbb as b
on
    a.id = b.id
where
    a.age = 18 and b.add = 'qwe'

  right join:以表bbb为主表,会把连接之后bbb表中的数据全部显示出来,即便aaa表中的没有与之对应的id 也会查询出来。

select a.name, b.name
from
    aaa as a
right join
    bbb as b
on
    a.id = b.id
where
    a.age = 18 and b.add = 'qwe'

   FULL JOIN:全外连接,全外连接等效于左外连接加上右外连接,返回左表和右表中所有的数据行。全外连接使用关 键字 FULL OUTER JOIN 表示,也可以简写成 FULL JOIN。

select a.name, b.name
from
    aaa as a
full join
    bbb as b
on
    a.id = b.id
where
    a.age = 18 and b.add = 'qwe'
  FULL JOIN:当连接查询没有指定任何连接条件时,就称为交叉连接。交叉连接使用关键字 CROSS JOIN 表示,也称为笛卡尔积(Cartesian product)。
  两个表的笛卡尔积相当于一个表的所有行和另一个表的所有行两两组合,结果数量为两个表 的行数相乘。假如第一个表有 100 行,第二个表有 200 行,它们的交叉连接将会产生 100 × 200 = 20000 行结果。
select a.name, b.name
from
    aaa as a
cross join
    bbb as b
on
    a.id = b.id
where
    a.age = 18 and b.add = 'qwe'

8.子查询

  in:

select * 
from
    aaa
where
    emp_id in (select id from emo_table where name = 'qqq')

  exists:

select *
from
    table1 t1
where exists (select 1 from table2 t2 where t1.id = t2.id)


select *
from
    table1 t1
where not exists (select 1 from table2 t2 where t1.id = t2.id)

 

posted @ 2023-11-15 22:43  手可摘星辰。  阅读(12)  评论(0编辑  收藏  举报