包含所有值的下拉选项,以 FK 形式保存到数据库
假设我有一个表“产品”,其中包含 3 个产品 ID:1、2 和 3。
然后在我的 asp.net 应用程序中,我有一个下拉菜单来选择具有以下选项的产品:
- 产品 1(值为 1)
- 产品 2(值为 2)
- 产品 3(值为 3)
- 任何产品(值为 0)
如果选择“任何产品”,我将返回与 3 个产品中的任何一个相匹配的 SQL 查询。
另一方面,我也必须保存每个搜索。
由于“Searches”表具有 ProductID 的 FK,因此问题是:
是否可以在 ProductID 中使用 NULL 值保存“任何产品”的搜索?因为它是一个FK,而且我一直在读FK 不应该为空。
我不确定是否有更好的方法(我不想在产品表中输入名为“任何产品”的新产品,这对我来说没有意义)。
非常感谢。
Let's say I have a table "Products" with 3 products ID: 1, 2 and 3.
Then in my asp.net app, I have a dropdown to select the product with these options:
- Product 1 (with value 1)
- Product 2 (with value 2)
- Product 3 (with value 3)
- Any product (with value 0)
If "any product" is selected, I return the SQL query that matches any of the 3 products.
On the other side, I also have to save each of these searches too.
As the "Searches" table has a FK of ProductID the question is:
Is it OK to save the searches of "Any product" with a NULL value in ProductID? Because it's a FK and I've been reading FK should not be null.
I'm not sure if there is a better way (I don't want to enter a new product called "Any product" to the table Products, it does not make sense to me).
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以按照你说的做,但是,当你说搜索表中的productid是外键时,你实际上对外键有约束吗?因为如果这样做,您将无法输入产品表中不存在的 null(或任何其他与此相关的值)。
例如,您可以创建一个 Id -1 的虚拟产品,当您从表中选择产品时,只需忽略 Id -1 的产品即可。
you could do as you say, BUT, when you say that the productid in the searches table is a foreign key, do you actually have a constraint for the foreign key? because if you do, you won't be able to enter null (or any other value for that matter) that doesn't exist in the product table.
you could create a dummy product with Id -1 for example, and when you select the products from the table, you just have to ignore the one with Id -1.
当然,将 ProductID 字段设置为 null 并不是一个好主意。将外键设置为 null 通常表明引用的字段已被删除或更新。
了解搜索表的确切用途将有助于找到问题的解决方案。但我的猜测是,您应该在代码中处理这种情况,而不是在数据库中。
Definitely, it is not a good idea to set to null your ProductID field. Setting a foreign key to null habitually indicate that the referenced field had been deleted or updated.
Knowing what exactly is the purpose of your Searches table would help to find a solution to your problem. But my guess is that you should treat this scenario in your code, not in the database.