连接表以连接每个可能的组合
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了连接表以连接每个可能的组合相关的知识,希望对你有一定的参考价值。
我有两个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 |
+----------+---------------------+
答案
你可以直接写:
SELECT CONCAT(a.ArticleNo,v.VariantNo) as ResultNo,
CONCAT(a.ArticleName,v.VariantName) as ResultName
FROM Article a,Variants v
它将产生交叉连接
另一答案
您正在寻找笛卡尔积。在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;
另一答案
我认为this正是你要找的。这种操作产生笛卡尔积。要解决您的问题,您应该从上面的链接应用此查询,它应如下所示:
select concat(ArticleNo,VariantNo ) as ResultNo ,
concat(ArticleName,VariantName) as ResultName
from Article
cross join Variants
以上是关于连接表以连接每个可能的组合的主要内容,如果未能解决你的问题,请参考以下文章