簡體   English   中英

從查詢聯接多行表返回單行

[英]Returning a single row from query joining multi-row tables

我有一個數據庫設計,可容納有關房屋的數據。 有2個(相關的)表-一個保存屬性代碼,名稱,描述等,第二個保存有關屬性屬性的信息。

目前,我在屬性表中有一些列(MaxDoubles,MaxSingles等),這些列包含非規范化數據,我現在需要(出於各種原因)將它們保存在屬性表中。 實際上,我將“屬性”表中的一系列列交換為“屬性”表中的一系列行。 所以我現有的查詢

從屬性中選擇MaxDoubles,MaxSingles

返回每個屬性一行的屬性需要重新編寫,以便在連接到屬性時也可以為每個屬性產生一行。 如果我嘗試

從屬性P中選擇SELECT A.MaxDoubles,A.MaxSingles,屬性A

那么我顯然會為每個屬性返回多個行。

有沒有一種巧妙的方法來聯接這些表,以便查詢結果返回一行?

謝謝

假設像@Konerak的示例這樣的架構,如果要包含屬性及其所有屬性的一行,則需要“透視”屬性記錄。

幸運的是,關於SO的信息並不缺乏 :)

您現在擁有的被稱為EAV數據結構,而您想要做的被稱為“樞紐”。 除了使用子選擇之外,還有兩種可能性。

使用GROUP BY:

SELECT P.Property_ID,
       MAX(IF(A.Type = 'maxsingles',A.Value,0)) AS MaxSingles,
       MAX(IF(A.Type = 'maxdoubles',A.Value,0)) AS MaxDoubles
FROM Properties P
JOIN Attributes A USING (Property_ID)
GROUP BY Property_ID

對每個屬性使用一個JOIN:

SELECT P.Property_ID, A1.Value AS MaxSingles, A2.Value AS MaxDoubles
FROM Properties P
JOIN Attributes A1 ON (A1.Property_ID = P.Property_ID AND A1.Type = 'maxsingles')
JOIN Attributes A2 ON (A2.Property_ID = P.Property_ID AND A2.Type = 'maxdoubles')

我們將需要您提供更多信息來解決您的問題。 例如:

您的表是什么樣子( SHOW CREATE TABLE Properties )您想執行什么查詢? 您如何加入餐桌?

此架構已足夠規范化以允許典型的所有查詢:

表屬性:

  • PropertyID
  • 屬性名稱
  • 物業描述

表格屬性:

  • AttributeID
  • PropertyID
  • AttributeName
  • 屬性值

因此,如果您擁有物業1,擁有3間卧室的白色房屋,則可以擁有

PropertyID: 1
PropertyName: Charming white landhouse with 3 spacious bedrooms
Propertydescription: This charming landhouse will ...

Attributes
AttributeID: 1
PropertyID: 1
AttributeName: NrBedrooms
AttributeValue: 3

AttributeID: 2
PropertyID: 1
AttributeName: NrBathrooms
AttributeValue: 2

AttributeID: 3
PropertyID: 1
AttributeName: Kitchen
AttributeValue: Fully Equiped

現在,如果您想知道您的房子有幾間卧室,您可以問

SELECT A.AttributeValue from Attributes A
INNER JOIN Properties P
ON P.PropertyID = A.PropertyID
WHERE P.PropertyID = 1
and A.AttributeName = 'NrBedrooms'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM