0

我有的:

一桌水果 食品(我从中选择水果),每个水果两排,小号一排,大号一排。

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

我需要的:

我需要将每个水果的两行合并为一行:

categorytitledescription对于每对行将始终相同。

每对行的idsubcategoryvalue总是不同的。

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 行

我的问题:

我应该如何修改上述查询以实现我所描述的?

4

1 回答 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

根据您是否可能缺少一些行,您可能需要 aleft outer joinfull outer join.

于 2013-04-22T19:01:55.710 回答