【SQL】查询两张关联table(a.pid=b.id)的数据sql语句

一、表信息:

两张表:bookinfor ; booktype ---- 图书信息表;图书分类表

建表语句:

1、 CREATE TABLE BOOKINFOR ( id int NOT NULL primary key, pid int NOT NULL ,name varchar(50) NULL,count int NOTNULL);

注释:id--自增;pid--对应的booktype中id;name --书籍名称;count --份数

2、CREATE TABLE BOOKTYPE ( id int NOT NULL primary key, typeName varchar(50) NULL, unit varchar(50) NULL,);

注释:id--自增;typename--类型名称;unit--所属单位

bookinfor 中的pid对应booktype 中id,指明此书所属类别


二、查询

目标: 已知booktype中typename= 教辅类,查询 bookinfor中包含在此类别下的所有书籍信息

查询语句1:select * from bookinfor where pid = (select a.id from booktype a where typename='教辅类')


查询语句2:select c.* from (select a.* ,b.id bid,b.typename btype,b.unit bunit from bookinfor a,booktype b where a.pid=b.id ) c where c.btype='教辅 ';


重点是语句2 将两张表合为一张表然后查询,并且可以查询到两张表的信息

猜你喜欢

转载自xuexin25.iteye.com/blog/1765302