在单行中获取多行的查询结果?

时间:2016-08-09 08:54:09

标签: mysql

我有一个表格,每一行都有产品详细信息,每个项目都是唯一的。第二个表格是税基,对任何单个项目都有多种税。我想要每个项目应该有单行的结果,并且与该项目相关的所有税收应该在该行中包含其他详细信息

item
item_id name type
1. bike vehicle

tax
id tax_name  tax_rate item_id
1. tax1       12        1
2. tax2       13        1
3. tax3       14        1

结果应该是:

id name type tax_name_1 tax_rate_1 tax_name_2 tax_rate_2 tax_name_3 tax_rate_3
1  bike vehicle tax1        12        tax2      13          tax3         14 

2 个答案:

答案 0 :(得分:0)

这是典型的表格枢轴问题,请尝试以下方法:

select
    item.*,
    max(case when tax.id = 1 then tax_name end) as tax_name_1,
    max(case when tax.id = 1 then tax_rate end) as tax_rate_1,
    max(case when tax.id = 2 then tax_name end) as tax_name_2,
    max(case when tax.id = 2 then tax_rate end) as tax_rate_2,
    max(case when tax.id = 3 then tax_name end) as tax_name_3,
    max(case when tax.id = 3 then tax_rate end) as tax_rate_3
from item
join tax
group by item.id

答案 1 :(得分:0)

我认为简单的内部联接将为您完成此任务

SELECT item.*, tax.taxname,tax.taxrate
    FROM table1
    INNER JOIN tax
    ON item.id=tax.id;