MySQL--多表查询

1. 基于笛卡尔积的多表查询

# 获取笛卡尔积
SELECT table1.field1, table2.field2
    FROM table1 INNER JOIN table2
或
SELECT table1.field1, table2.field2
    FROM table1, table2

1.1 内连接

SELECT table1.field1, table2.field2
    FROM table1 INNER JOIN table2
        ON table1.field1=[!= < > ...]table1.field2    # 获取笛卡尔积满足条件的那些行
或
SELECT table1.field1, table2.field2
    FROM table1, table2
        WHERE table1.field1=table2.field2

1.2 外链接

select *
from table1 left|right|full [outer ]join table2
on 条件;

2. 合并查询记录

select * from table1
union |union all
select * from table2
# union 把字段相同的查询结果合并到一起并去掉重复记录
# union all 只合并不去重

3. 子查询

select *
    from table1
        where field 比较运算符(
            返回单行单列的查询语句)

select *
    from table1
        where (field1, field2, ...)=(
            返回单行多列的查询语句)

select *
    from table1
        where field [NOT ]IN(
            返回多行单列的查询语句)

select *
    from table1
        where field >ANY(
            返回多行单列的查询语句)

select *
    from table1
        where field >ALL(
            返回多行单列的查询语句)
select *
  from table1
    where exists(
      select * from table2
        where 可含table1.field的条件);
# 遍历table1, 每一条都会执行一次where后面的语句
# 如果后面的select能查询到记录, 则当前遍历到的记录
# 被输出, 若后面select查询结果为空, 则当前遍历到的
# 记录被扔掉, 此例相当于把每个table1.field都传入
# 到后面执行一次select
# not exists与上述相反

FROM ... (查询语句) ...   可当做一个表使用

原文地址:https://www.cnblogs.com/P--K/p/8552004.html