您好,欢迎来到知库网。
搜索
您的当前位置:首页MySQL多表操作

MySQL多表操作

来源:知库网

外键约束

-- 给product中的cno添加一个外键约束
-- 修改表product给cno添加外键并且关联到category表的cid上面
-- references关联的列必须是主键
alter table product add foreign key(cno) references category(cid);
-- 如果添加了外键约束,比如说向product表中添加了一个cno在category中cid不存在的值,则会失败,同理添加外键时候如果不匹配也会失败。

-- 建表的时候创建外键
create table student(
    oid int ,
    pid int,
    foreign key(oid) references user(kid)
    foreign key(pid) references order(id)
)

唯一约束和主键约束


  • 唯一约束:列表内容必须唯一,但是可以为空 unique
    • 不能作为其它表的外键
    • 可以有多个
  • 主键约束: 默认必须不能为空且唯一
    • 外键一般都是指向另外一张表的主键
    • 一张表只能有一个

多表查询

-- 交叉连接查询(笛卡儿积)
-- 查询了两张表(一般结果无意义,不过可以通过条件过滤,例如where)
select * from product p,student s where 

-- 内连接查询
-- 隐式内链接
select * from product p,student s where 
-- 显式内链接(效果同上,on后面跟条件)
select * from product p inner join student s on 

-- 外连接查询
-- 左外连接(左表中数据全部查询出来,如果右边没遇对应的数据则显示NULL)
select * from product p left outer join student s on 

-- 右外连接(右表中数据全部查询出来,如果左边没遇对应的数据则显示NULL)
select * from product p right outer join student s on 

> 内外连接在查询结果上面的区别就是内链接必须匹配条件而且无null值一般

-- 分页查询
select * from student limit 1 ,10;
-- 子查询
select * from student where age>(select cage from  people where name='sdas');
select pname,(select cname from catergory c where  from product p;
补充:大部分情况下,连接查询和子查询可以互用

Copyright © 2019- zicool.com 版权所有 湘ICP备2023022495号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务