从连接多行表的查询中返回单行
我有一个数据库设计,用于保存有关房屋的数据。有 2 个(相关)表 - 第一个保存属性代码、名称、描述等,第二个保存有关属性属性的信息。
目前,我在属性表中有列(MaxDoubles、MaxSingles 等),这些列保存了我现在需要(出于各种原因)在属性表中保存的非规范化数据。实际上,我将“属性”表中的一系列列交换为“属性”表中的一系列行。所以我现有的查询
SELECT MaxDoubles, MaxSingles 每个属性返回一行的FROM 属性
需要重写,以便在连接到属性时也为每个属性生成一行。如果我尝试
SELECT A.MaxDoubles, A.MaxSingles FROM Properties P, Attributes A
然后我显然会得到每个属性返回的多行。
是否有一种巧妙的方法来连接这些表,以便查询结果返回一行?
谢谢
I have a database design that holds data about houses. There are 2 (relevant) tables - one holds property code, name, description etc, and the second holds information about attributes of the property.
Currently I have got columns in the property table (MaxDoubles, MaxSingles etc) that hold denormalised data that I need to now hold (for various reasons) in the attributes table. In effect I am swapping a series of columns in the Properties table for a series of rows in the Attributes table. So my existing query
SELECT MaxDoubles, MaxSingles
FROM Properties
that returns one row per property needs re-writing to also produce one row per property when joined to the Attributes. If I try
SELECT A.MaxDoubles, A.MaxSingles
FROM Properties P, Attributes A
then I obviously get multiple rows returned per property.
Is there a clever way of joining these tables so the query result returns a single row?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设像 @Konerak 的示例这样的模式,如果您希望一行包含属性及其所有属性,则需要“旋转”属性记录。
幸运的是,不乏关于如何做到这一点的信息。 :)
Assuming a schema like @Konerak's example, you'll need to "pivot" the attributes records if you want one row containing a property and all of its attributes.
Fortunately, there is no shortage of info on SO about how to do that. :)
您现在拥有的称为 EAV 数据结构 而你想做的就是“转向”。除了使用子选择之外,还有两种可能性。
使用 GROUP BY:
对每个属性使用一个 JOIN:
What you now have is called an EAV data structure and what you want to do is called "to pivot". Besides using a subselect, there are two possibilities.
Using a GROUP BY:
Using one JOIN for each attribute:
我们需要您提供更多信息来处理您的问题。例如:
您的表是什么样的(
SHOW CREATE TABLE Properties
)您想要执行什么查询?
你如何加入你的桌子?
此架构已标准化,足以允许典型的所有查询:
表属性:
表属性:
因此,如果您拥有房产 1,则拥有 3 号房产的白宫卧室,你可以有
现在如果你想知道你的房子有多少间卧室,你可以问
We'll need more information from you to handle your question. For example:
What do your tables look like (
SHOW CREATE TABLE Properties
)What queries do you want to execute?
How do you join your tables?
This schema is normalized enough to allow typical all queries:
Table Properties:
Table Attributes:
So if you have Property 1, a white house with 3 bedrooms, you could have
Now if you want to know how many bedrooms your house has, you can ask