Mysql:如何构造这些数据并搜索它
我是 mysql 的新手。现在,我在 mysql 数据库中有这种结构:
| keyID | Param | Value
| 123 | Location | Canada
| 123 | Cost | 34
| 123 | TransportMethod | Boat
...
...
我可能有 20 个参数,每个键 ID 都有唯一的值。我希望能够在 mysql 中搜索给定的 20 个参数以及每个值并找出哪个 keyID。
首先,我应该如何重构mysql数据库?我应该有 20 个参数列 + keyID 吗? 其次,(与第一个问题相关),我将如何进行查询来查找 keyID?
I'm new to mysql. Right now, I have this kind of structure in mysql database:
| keyID | Param | Value
| 123 | Location | Canada
| 123 | Cost | 34
| 123 | TransportMethod | Boat
...
...
I have probably like 20 params with unique values for each Key ID. I want to be able to search in mysql given the 20 params with each of the values and figure out which keyID.
Firstly, how should I even restructure mysql database? Should I have 20 param columns + keyID?
Secondly, (relates to first question), how would I do the query to find the keyID?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的参数在不同的键上是相同的(或者所有参数都是对象可能具有的某组参数的子集),则您应该构建数据库,以便每一列都是一个参数,并且该行对应于一个 KeyID 和值它的参数。
然后要查询 keyID,您可以使用 SELECT、FROM 和 WHERE 语句,例如,
有关详细信息,请参阅 http://www.w3schools.com/php/php_mysql_where.asp
编辑:如果您的参数在不同对象(keyID)之间发生变化,我认为这将需要不同的方法
If your params are identical across different keys (or all params are a subset of some set of params that the objects may have), you should structure the database so that each column is a param, and the row corresponds to one KeyID and the values of its params.
Then to query for the keyID you would use a SELECT, FROM, and WHERE statement, such as,
for more info see http://www.w3schools.com/php/php_mysql_where.asp
edit: if your params change across different objects (keyIDs) this will require a different approach I think
您展示的设计称为“实体-属性-值”。它打破了关系数据库设计的许多规则,并且很难与 SQL 一起使用。
在关系数据库中,每个属性类型都应该有一个单独的列。
The design you show is called Entity-Attribute-Value. It breaks many rules of relational database design, and it's very hard to use with SQL.
In a relational database, you should have a separate column for each attribute type.
我同意尼克的答案可能是最好的,但如果你真的想保留你的键/值格式,你可以用视图来完成你想要的(这是 PostgreSQL 语法,因为这就是我的意思)我很熟悉,但 MySQL 的概念是相同的):
这里的性能可能很差,但如果您的查询不频繁,它可以完成工作。
I agree that Nick's answer is probably best, but if you really want to keep your key/value format, you could accomplish what you want with a view (this is in PostgreSQL syntax, because that's what I'm familiar with, but the concept is the same for MySQL):
Performance here is likely to be dismal, but if your queries are not frequent, it could get the job done.