![](/img/trans.png)
[英]Can I randomly select a row from one table and use a static identifier to select corresponding data in another table?
[英]How do i limit in sql, that if one table row is selected, only corresponding items from another table show?
例如,我有两个表,名称分别为“服装”和“颜色”
现在我要限制一下,当选择某个项目时可以选择哪种颜色。
示例:我在“服装”中有以下两项:裤子和T恤。 还有3种颜色:红色,绿色和黑色。
现在,当我选择“裤子”时,我只希望能够选择红色和绿色。 当我选择T恤时,只有黑色和绿色。
我试过的是:
创建一个名为“ clothing”的表,其中包含列ID,名称
用列ID,名称和服装ID(外键)创建一个名为“颜色”的表
用列ID,clothingID(外键)和colorID(外键)创建一个名为“ order”的表
我的桌子“衣服”:
ID:1; 名称:裤子
ID:2; 名称:T恤
之后,我用以下4个项目填充了“颜色”表:
ID:1; 名称:红色; 服装编号:1
ID:2; 名称:绿色; 服装编号:1
ID:3; 名称:黑色 服装编号:2
编号:4; 名称:红色; 服装编号:2
现在,“订单”表应该无法选择例如红色T恤。 但是,它不起作用。 我不知道如何前进,因为我的“颜色”表中有些多余的东西,也不知道在哪里搜索以解决问题...
假设这些是您餐桌上的clothing
和order
:
create table clothing(id int primary key, name varchar(20));
insert into clothing(id, name) values
(1, 'pants'), (2, 'tshirt');
create table color(id int primary key, name varchar(20));
insert into color(id, name) values
(1, 'red'), (2, 'green'), (3, 'black');
现在创建另一个表格clothingcolor
,在其中存储要允许的服装和颜色的组合:
create table clothingcolor(
clothingid int,
colorid int,
PRIMARY KEY (clothingid, colorid),
FOREIGN KEY (clothingid) REFERENCES clothing(id),
FOREIGN KEY (colorid) REFERENCES color(id)
);
insert into clothingcolor(clothingid, colorid) values
(1, 1), (1, 2), (2, 1), (2, 3);
最后您的order
表:
create table `order`(
id int,
clothingid int,
colorid int,
FOREIGN KEY (clothingid, colorid) REFERENCES clothingcolor(clothingid, colorid)
)
包含引用表的复合外键clothingcolor
所以你只能存储clothingid
和colorid
存在于表组合clothingcolor
。
参见演示 。
此设计仅供参考。
如果您决定实施,将会有其他问题需要解决。
首先,您应该为这两个实体创建一个联接表(用clothingID和colorID作为外键和主键),然后您只需要执行查询以选择正确的对象。
例如:订购:红色T恤
查询:
select * from clothing c1 join clothingColors cc on c1.id = cc.clothingID join on colors c2 on cc.colorID = c2.id where c1.name = "t-shirt" and c2.name = "red"
在您的情况下,此查询应返回null。
在名为“ order”的表上,其中具有ID列,clothingID和colorID的列将外键同时包含ClothingID和colorId。 现在,您将它们作为单独的外键使用,它们分别是有效的,但是组合起来它们将无效。 您需要在颜色表上创建唯一索引,以具有服装ID和颜色ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.