连接表以连接每个可能的组合

时间:2018-03-16 12:22:58

标签: mysql join

我有两个mysql表。一个有文章编号,一个有变种编号。 不,我想加入表格,所以有一个结果表,包含每个可能的文章/变体组合。 例如:

物品编号表:

+-----------+-------------+
| ArticleNo | ArticleName |
+-----------+-------------+
|      0001 | Product 1   |
|      0002 | Product 2   |
|      0003 | Product 3   |
+-----------+-------------+

变体数字表:

+-----------+-------------+
| VariantNo | VariantName |
+-----------+-------------+
|      1001 | Variant 1   |
|      1002 | Variant 2   |
|      1003 | Variant 3   |
+-----------+-------------+

结果表:

+----------+---------------------+
| ResultNo |     ResultName      |
+----------+---------------------+
| 00011001 | Product 1 Variant 1 |
| 00011002 | Product 1 Variant 2 |
| 00011003 | Product 1 Variant 3 |
| 00021001 | Product 2 Variant 1 |
| 00021002 | Product 2 Variant 2 |
| 00021003 | Product 2 Variant 3 |
| 00031001 | Product 3 Variant 1 |
| 00031002 | Product 3 Variant 2 |
| 00031003 | Product 3 Variant 3 |
+----------+---------------------+

3 个答案:

答案 0 :(得分:2)

您正在寻找笛卡尔积。在SQL中,这是通过CROSS JOIN

提供的
select concat(a.ArticleNo, v.VariantNo) as ResultNo,
       concat_ws(' ', a.ArticleName, v.VariantName) as ResultName
from articles a cross join
     variants v
order by a.ArticleName, v.VariantName;

答案 1 :(得分:2)

你可以直接写:

SELECT  CONCAT(a.ArticleNo,v.VariantNo) as ResultNo, 
CONCAT(a.ArticleName,v.VariantName) as ResultName 
FROM Article a,Variants v

它将产生交叉连接

答案 2 :(得分:-1)

我认为this正是您所寻找的。这种操作产生笛卡尔积。要解决您的问题,您应该从上面的链接应用此查询,它应如下所示:

select concat(ArticleNo,VariantNo ) as ResultNo ,
concat(ArticleName,VariantName) as  ResultName 
from Article 
cross join Variants