加入数据 - 排成一列?

时间:2016-06-02 16:32:46

标签: mysql sql

即时通讯请帮帮我。

表1

id, options1, options2, options3
-----------------------------------------
1, 'a', 'b', 'c'
2, 'x', 'b', 'c'
3, 'c', 'b', 'd'
4, 'z', 'b', 'c'

表2

id, productid, name
-------------------
1, 1, "Title"
2, 1, "Color"
3, 2, "Title"
4, 3, "Title"
5, 4, "Title"
6, 4, "Color"
7, 4, "Size"

// product_id的不同行数(min = 0和max = 3)

如何获得: 表3

productid, new_name
--------------------
1, "Title a; Color b; c"
2, "Title x; b; c"
3, "Title c; b, d"
4, "Title z; Color b; Size c" 

1 个答案:

答案 0 :(得分:0)

好的,我发表了评论,但我没有声望点,但我想帮助你。

您的架构有点不对劲。这些表应该可以通过ID或productID连接。如果您运行以下查询,您会注意到这些查询没有产生您想要的结果,并且无法将table1中的选项附加到table2中的产品:

select table2.productid, * from table1 
full outer join table2 on table1.id = table2.id

select table2.productid, * from table1 
full outer join table2 on table1.id = table2.productid

您可以纠正表2:

table2
productid
id
value1 as nullable
value2 as nullable
value3 as nullable

由于我的数据库中没有这些表格,因此我立即入侵了这张表:

select 1 as id , 1 as productid , 'Title' as value1,'Color' as value2, null as value3  union
select 2 as id , 2 as productid , 'Title' as value1, null , null  union
select 3 as id , 3 as productid , 'Title' as value1, null , null  union
select 4 as id , 4 as productid , 'Title' as value1, 'Color' as value2, 'Size' as value3

这样您的选项就会匹配其值:

select 
    value1, options1,
    value2, options2,
    value3, options3
  from table1 join table2 on table1.id=table2.id

这可以进一步细化为

select 
    productid,
    coalesce(value1,'') +' '+ coalesce(options1,'') + '; ' +
    coalesce(value2,'')+' '+ coalesce(options2,'') +'; '+
    coalesce(value3,'')+' '+ coalesce(options3,'') as new_name
     from  #tb3 join #tb1 on #tb3.id=#tb1.id

产生您需要的结果:

productid   new_name
----------- ------------------------
1           Title a; Color b;  c
2           Title x;  b;  c
3           Title c;  b;  d
4           Title z; Color b; Size c

但是,更好的方法是创建另一个具有单独选项的表,在该表中您可以有1个或多个选项(超过3个)

请注明答案是否适合您。感谢

相关问题