--創建數據庫 create database GoodsSystem go --使用數據庫 use GoodsSystem go --創建商品類型表 create table GoodsType ( IO int primary key identity(1,1), typename varchar(10)not null ) go --創建商品信息表 create table Goods ( Id int primary key identity(1,1), Typeld int foreign key references GoodsType(IO), Name varchar(20)not null, Price decimal(10,2) not null, ProductionDate datetime not null, Amount int not null ) go
插入數據
insert into GoodsType values ('家電'), ('電子'), ('食品'), ('生活用品') insert into Goods values ('1','冰箱',3344,'2017-06-03',100), ('1','電視',1777,'2016-06-03',100), ('1','微波爐',333,'2017-02-26',100), ('2','手機',4500,'2017-05-07',100), ('2','顯示器',1777,'2016-12-04',100), ('2','主機',1500,'2017-03-09',100), ('3','老干媽',9,'2017-07-06',100), ('3','爽口榨菜',3.6,'2017-06-08',100)
查詢:
select * from GoodsType select * from Goods
--內連接(inner可以不寫) select g1.name,g2.Name,price,productiondate,g2.Amount FROM GoodsType g1 inner join Goods g2 on g1.IO=g2.Typeld select * from Goods select * from GoodsType --外連接分(左外連接)和(右外連接) --左外連接( left join) select g2.Name,Price,ProductionDate,Amount,g1.name FROM Goods G1 left join GoodsType G2 on G1.Typeld=G2.IO --右外連接(right join--空值的會顯示出來) select g2.Name,Price,ProductionDate,Amount,g1.name FROM Goods G1 right join GoodsType G2 on G1.Typeld=G2.IO --全外連接(full outer(可以不寫) join--空值的會顯示出來) select g1.name,g2.Name,price,productiondate,g2.Amount FROM GoodsType g1 full outer join Goods g2 on g1.IO=g2.Typeld --交叉連接(笛卡爾積)查詢所有的值 select g1.name,g2.Name,price,productiondate,g2.Amount FROM GoodsType g1 cross join Goods g2 where g1.IO=g2.Typeld