通过另一个表组合两个表

时间:2011-12-14 11:03:03

标签: sql database join

我有一个典型的N-M关系结构:

两个独立的表格:

Table Client:
id | name
1  | Joe
2  | Marc

Table Product:
id | name
1  | Toyota
2  | Ford
3  | Fiat

和链接表如:

Table Purchase:
idClient | idProduct | Paid
1        | 1         | 3000
1        | 2         | 2999
2        | 3         | 4500
2        | 1         | 1000

我想要一个产生的查询:

client | Toyota | Ford | Fiat
Joe    |  3000  | 2999 | 
Marc   |  1000  |      | 4500

有没有办法在MySQL中做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在尝试进行PIVOT查询; stackoverflow上有很多例子。搜索Pivot和MySQL。

例如,这是使用CASE语句的一个: SQL query to pivot a column using CASE WHEN

答案 1 :(得分:1)

就像@StuartAinsworth所说,你需要做一个Pivot查询。


对于动态方法,请使用:

create table Client (
id int,
name varchar(10)
)

insert into Client values (1, 'Joe')
insert into Client values (2, 'Marc')

create table Product (
id int,
name varchar(10)
)

insert into Product values (1, 'Toyota')
insert into Product values (2, 'Ford')
insert into Product values (3, 'Fiat')

create table Purchase (
idClient int,
idProduct int,
Paid int
)

insert into Purchase values (1, 1, 3000)
insert into Purchase values (1, 2, 2999)
insert into Purchase values (2, 3, 4500)
insert into Purchase values (2, 1, 1000)


declare @cmd varchar(2048)
declare @prod varchar(10), @count int, @total int

select @cmd = 'select c.name, '

select @count = 1, @total = max(id) from Product

while @count <= @total
begin
    select @prod = name from Product where id = @count

    if(@count <> @total)
    begin
        select @cmd = @cmd + 'sum(CASE WHEN p.name = "' + @prod + '" THEN u.Paid ELSE 0 END) as "' + @prod + '", ' 
    end
    else   
    begin
        select @cmd = @cmd + 'sum(CASE WHEN p.name = "' + @prod + '" THEN u.Paid ELSE 0 END) as "' + @prod + '" ' 
    end
    select @count = @count + 1
end

select @cmd = @cmd + 'from Client c ' +
 + 'inner join Purchase u on u.idClient = c.id ' +
 + 'inner join Product p on p.id = u.idProduct ' +
 + 'group by c.name'


exec(@cmd)

drop table Client
drop table Product
drop table Purchase