SQL:将1个表中的2行组合为1,从而为子查询生成多行

时间:2013-04-22 18:57:45

标签: mysql sql database phpmyadmin

我拥有的:

一个 fruit 食物(我从中选择水果)的表格,每个水果各两行,一个用于小尺寸,一个用于大尺寸。< / p>

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行

我的问题:

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

1 个答案:

答案 0 :(得分: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