现在有一个产品表Products,一个类型表,ProType。
产品表:
id name type
25 电视机 1类型表:
id name
1 家用电器如何查询能够显示出来这样的效果:
id name type
25 电视机 家用电器还有,这两个表必须建立关联吗?
产品表:
id name type
25 电视机 1类型表:
id name
1 家用电器如何查询能够显示出来这样的效果:
id name type
25 电视机 家用电器还有,这两个表必须建立关联吗?
Products a left join ProType b on a.type=b.type
select a.id,a.name,b.type from
Products a left join ProType b on a.type=b.id --这个地方我刚才写错了,更正一下
那我要是想更新下产品的类别呢?也能用left join?怎么写才好呢?
先根据类别名称查询到类别id,然后再更新?
where [Products].[type]=[ProType].[id]
------------------------------------------------------
select [Products].[id],[Products].[name],[ProType].[name] As [type] from [Products],[ProType] where [Products].[type]=[ProType].[id]
如果是字符类型就可以。declare @产品表 table (id int,name varchar(6),[type] varchar(40))
insert into @产品表
select 25,'电视机','1'declare @类型表 table (id int,name varchar(8))
insert into @类型表
select 1,'家用电器'--查看结果:
select a.id,a.name,b.name AS TYPE from
@产品表 a left join @类型表 b on a.type=b.id
/*
id name TYPE
----------- ------ --------
25 电视机 家用电器
*/--更新操作
update @产品表
set [type]=b.name
from
@产品表 a left join @类型表 b on a.type=b.idselect * from @产品表
/*
id name type
----------- ------ ----------------------------------------
25 电视机 家用电器
*/
LEFT JOIN ProType T1
ON T.ID=T1.ID
select a.id,p.name,b.name from Products a,ProType b where a.type=b.id