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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值