【问题标题】:Data Definition Language (DDL) Query SQL数据定义语言 (DDL) 查询 SQL
【发布时间】:2018-10-31 19:30:07
【问题描述】:

我是查询和 SQL 服务器的新手,我想了解 DDL。 我的表中有一个属性超过 1 个值,例如 尺寸 = {'S'、'M'、'L'}。 如何使用查询在我的表中创建属性,以便我可以向我的属性之一插入多个值?

【问题讨论】:

  • 您不会将多个属性插入一行。您将多行插入到一个表中。
  • 查找一对多关系,这种事情你会使用两个表
  • 产品 (...,ProductSize); INSERT INTO Product (ProductSize) VALUES ('S') 如何查询 ProductSize 的行以便我可以在 SQL 中插入多个值?
  • @Brad 的建议在这里是正确的

标签: sql sql-server ddl


【解决方案1】:

您不想这样做,因为这会使您的数据非规范化。但是,如果必须的话。

declare @table table (id int identity(1,1),  size varchar(16))

insert into @table
values
('S')
,('M')

select * from @table

update @table
set size = size + ',M'
where id = 1

select * from @table

这是使用外键的一对多方法

create table #items (id int identity(1,1), descrip varchar(64))

insert into #items
values
('shirt'),
('pants')

create table #item_sizes (id int identity(1,1), size char(1), item_id int)
alter table #item_sizes
add constraint FK_item foreign key (item_id) references #items(id)

insert into #item_sizes
values
('S',1)
,('M',1)
,('L',1)
,('S',2)

select 
    ItemID = i.id
    ,i.descrip
    ,isiz.size
from #items i
inner join #item_sizes isiz
on isiz.item_id = i.id


drop table #items, #item_sizes

【讨论】:

    【解决方案2】:

    根据您的要求:

    产品 (...,ProductSize);

     INSERT INTO Product (ProductSize) VALUES ('S')
    

    如何查询 ProductSize 的行以便我可以在 SQL 中插入多个值? ——

    您可以像下面这样查询

     select * from Product where ProductSize like '%S%' or ProductSize like '%L%' or ProductSize like '%M%' 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-27
      • 2023-01-20
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2011-09-20
      相关资源
      最近更新 更多