【问题标题】:How to merge 2 columns with all possible combinations in SQL?如何将 2 列与 SQL 中的所有可能组合合并?
【发布时间】:2015-03-26 11:06:40
【问题描述】:

这个问题听起来令人困惑,但请看:

这样我们就可以得到第一列(col1):

select distinct maker
from product

还有第二列(col2):

select distinct type,maker
from product

所以现在我需要从 col1 和 col2 中获取所有可能的组合。有什么建议吗?

很快,这个:

A f1

B f2

应该变成这样:

A f1

A f2

B f1

B f2

附:此查询不会返回我需要的。

select distinct A.maker, B.type
from product as A

【问题讨论】:

    标签: sql merge combinations ansi-sql


    【解决方案1】:

    使用cross join 获取所有组合:

    select m.maker, t.type
    from (select distinct maker from product) m cross join
         (select distinct type from product) t;
    

    这是 ANSI SQL 语法,任何数据库都应支持。

    【讨论】:

      【解决方案2】:

      使用cross join 但没有子查询的变体将给出与@Gordon Linoff 帖子中相同的结果,因此您将获得所有可能的组合

      select distinct A.maker, B.type
      from product as A cross join product as B
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多