【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 将两张表合为一张表然后查询,并且可以查询到两张表的信息

优化这段代码 protected virtual PlatformCustomerRecordExcel QueryExcel(SearchCompanyByProjectReq input, StringBuilder sql) { PlatformCustomerRecordExcel result = new PlatformCustomerRecordExcel(); using (var db = GetReadDb()) { var list = new PagedResult<SearchPlatformCustomerResult>(); string where = sql.ToString(); result.PlatforCompanyData = db.SqlQueryable<PlatforCompanyData>($@" select b.PID,b.CompanyName,b.OrganizationCode,bi.DetailedAddress,bi.OperationState from MallDataBase.Platform_BusinessMain b inner join {TABLE_NAME} c on b.PID=c.CompanyId INNER JOIN malldatabase.platform_businesslicense bi on b.PID=bi.PID where b.IsDelete=0 and bi.IsDelete=0 and c.IsDelete=0 {where} ").OrderByIF(input.OrderBy.IsNotEmpty(), input.OrderBy).ToList(); result.PlatforCompanyFinancing = db.SqlQueryable<PlatforCompanyFinancing>($@" select f.CompanyID,f.FinancingTime,f.FinanceScale,f.FinanceMode,f.Shareholder from MallDataBase.Platform_BusinessMain b inner join {TABLE_NAME} c on b.PID=c.CompanyId INNER JOIN crmdatabase.view_company_years_financing f on b.PID=f.CompanyId where b.IsDelete=0 and c.IsDelete=0 {where} and not f.FinanceMode like '%退市%' ").ToList(); result.PlatforCompanyTag = db.SqlQueryable<PlatforCompanyTag>($@" select etl.CompanyID,etl.Tagid from MallDataBase.Platform_BusinessMain b inner join {TABLE_NAME} c on b.PID=c.CompanyId INNER JOIN malldatabase.view_ent_tagrelation_list etl on b.PID=etl.CompanyId where b.IsDelete=0 and c.IsDelete=0 {where} and not f.FinanceMode like '%退市%' ").ToList(); } return result; }
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值