2013-04-22 81 views
0

我有什麼:

表具有兩列 水果 食品(我從中選擇水果)

一每個水果,一個小尺寸,一個大尺寸。SQL:從表1分的結果多行合併2行至一個子查詢

id | category | subcategory | title | description  | value 
----------------------------------------------------------------- 
1 | Fruit | Small  | Plum | Om, nom, nom!  | 0.50 
2 | Fruit | Large  | Plum | Om, nom, nom!  | 1.50 
3 | Fruit | Small  | Orange | Mmm, citrus.  | 0.30 
4 | Fruit | Large  | Orange | Mmm, citrus.  | 0.75 
5 | Fruit | Small  | Melon | Get in mah belly! | 2.00 
6 | Fruit | Large  | Melon | Get in mah belly! | 3.10 

我需要什麼:

我需要兩行對每個水果組合成一排:

冠軍描述將始終是相同的爲每一對行。

ID子類別將永遠爲每對行的不同。

id.r1 | id.r2 | category.r1 | title.r1 | description.r1  | subcategory.r1 | value.r1 | subcategory.r2 | value.r2 
----------------------------------------------------------------------------------------------------------------------- 
1  | 2  | Fruit  | Plum  | Om, nom, nom!  | Small   | 0.50  | Large   | 1.50 
3  | 4  | Fruit  | Orange | Mmm, citrus.   | Small   | 0.30  | Large   | 0.75 
5  | 6  | Fruit  | Melon  | Get in mah belly! | Small   | 2.00  | Large   | 3.10 

我已經試過什麼:

SELECT r1.id, 
(SELECT r2.id FROM `my_table` r2 WHERE r1.title = r2.title), 
r1.category, 
r1.subcategory, 
(SELECT r2.category FROM `my_table` r2 WHERE r1.title = r2.title) 
r1.title, 
r1.description, 
r1.value, 
(SELECT r2.value FROM `my_table` r2 WHERE r1.title = r2.title) 

FROM `my_table` r1 

WHERE category = "Fruit" 

...主要生產:

子查詢返回多個1行

我的問題:

如何修改上述查詢以實現我所描述的內容?

回答

3

你可以很容易地做到這一點與聚合:

select category, title, description, 
     MAX(case when subcategory = 'Small' then id end) as Small_Id, 
     MAX(case when subcategory = 'Small' then value end) as Small_Value, 
     MAX(case when subcategory = 'Large' then id end) as Large_Id, 
     MAX(case when subcategory = 'Large' then value end) as Large_Value 
from my_table f 
group by category, title, description 

注:這不包括在最終結果subcategory因爲該行沒有子類別。

你也可以做到這一點的加盟,這似乎是你正在採取的路徑:

select fsmall.id, flarge.id, fsmall.category, flarge.category, . . . 
from my_table fsmall join 
    my_table flarge 
    on fsmall.subcategory = 'small' and flarge.subcategory = 'large' and 
     fsmall.category = flarge.category and 
     fsmall.title = flarge.title and 
     fsmall.description = flarge.description 

根據是否可能有一些失蹤行,你可能需要一個left outer joinfull outer join

+0

感謝您選擇解決方案和每個解釋。解決方案1:這很好。我明白你的意思是關於子類別。子類別的值是在ID和值的列標題中表示的。解決方案2:我無法正確直觀地確認它是否有效以及生成的行是否相同。應該「水果」(類別值)不是「我的表」(表的名稱)還是我的方式離開的標誌?此外,是省略號(...)功能還是我假設其他列將被添加?非常感謝您的幫助。 – 2013-04-22 19:21:07

+0

@DominorNovus。 。 。我把桌子叫做'水果',但是我只是用'my_table'替換了你的問題。這是否解決您的問題? – 2013-04-22 19:23:47

+0

是的,謝謝。我修改了第二個解決方案的列選擇,並在查詢結尾處添加了WHERE條件。最終結果與第二種解決方案產生了完全相同的記錄量。修改後的代碼:http://pastebin.com/1BDfWbC9 – 2013-04-22 19:40:43