数据库中的二键表?
我正在尝试设计一个数据库表,其中列出“城市 A”到“城市 B”的距离“价格”。 B城市到A城市的价格应该是相同的,因此将此信息存储两次是多余的。
我应该如何设计表格,以便给定 2 个城市,我可以查找价格而不必存储两次(如 A,B,price
和 B,A,price
)?
我的想法是,我可以“按字母顺序”存储它,这样“较早”的城市将始终位于左列中,而较晚的城市将出现在右列中。然后,在查询数据库时,我只需要做同样的事情,并在必要时交换顺序。
I'm trying to design a database table that lists "prices" for distances, "City A" to "City B". City B to City A should be the same price, so it would be redundant to store this information twice.
How should I design the table such that given 2 cities, I can look up the price without having to store it twice (as A,B,price
and B,A,price
)?
My idea is that I can store it "alphabetically" such that the "earlier" city would always be in the left column, and the later city would appear in the right column. Then when querying the DB, I just have to do the same thing and swap the order if necessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,你可以在 select (WHERE (A = 'city A' and B= 'city B') Or (A = 'city B' and B= 'city A') 中使用 OR 子句来做到这一点,但要诚实地存储它两次可能意味着更快的查询。
Well you can do that with an OR clause in your select (WHERE (A = 'city A' and B= 'city B') Or (A = 'city B' and B= 'city A'), but honestly storing it twice will probaly mean faster querying.
最好的快速通用解决方案可能是接受约束,例如所有行中的 CityId1
如果更多的是关于“数据库设计”,那么只需将其输入您最喜欢的 ER 建模工具,然后观察结果即可。
Probably the best fast&generic solution is to live with a constraint, for example CityId1<CityId2 in all rows, and use some kind of OR or double select when retrieving the data from the table.
If it's more about "database design", then just feed it into your favorite ER modeling tool, and observe the result.
城市对在表中仅存储一次。使用存储过程按字母顺序存储数据,并将第一个字母城市存储在第一列中,以便在插入之前对数据进行排序。在两个城市列上创建唯一索引。创建一个检索存储过程,该过程将首先对提供的城市进行排序,然后查询表。以下是使用 SQL Server 2K8 Express 的一些快速工作。
Store the city pairs only once in the table. Store the data in alpha order with the first alpha city in the first column using a stored procedure to sort the data prior to insertion. Create a unique index on the two city columns. Create a retrieval stored procedure which will sort the supplied cities first then query the table. Here is some quick work using SQL Server 2K8 Express.
您正在谈论复合键的概念,其中 value_1 和 value_2 都确定提取哪条记录。
我想说,只需将其设计在您的字段 city_1、city_2、price 的位置即可。然后以编程方式处理逻辑来定义正确的查询。
You are speaking of the concept of the compound key, where both value_1 and value_2 determine which record is pulled.
I would say simply design it where your fields would city_1, city_2, price. Then programmatically handle the logic to define the proper query.