【问题标题】:generating conditional combinations in sql在sql中生成条件组合
【发布时间】:2018-07-29 11:57:40
【问题描述】:

我有下表:

╔═══╦══════════════╦═════════════╗
║   ║id            ║name         ║
╠═══╬══════════════╬═════════════╣
║   ║ 1            ║a1           ║
║   ║ 1            ║b1           ║
║   ║ 2            ║b2           ║
║   ║ 3            ║c1           ║
║   ║ 2            ║c2           ║
║   ║ 4            ║a2           ║
╚═══╩══════════════╩═════════════╝

我有以下查询,它执行以下操作:

对于输入 (a,b,c),它返回 (aX,bX,cX) 形式的所有可能组合,其中 X 是记录中“a/b/c”之后出现的任何内容。

(a,b) 根据我的表格生成 (a1,b1) , (a1,b2) 。

运行此查询

select t1.id as t1_id, t1.name as t1_name,
t2.id as t2_id, t2.name as t2_name,
t3.id as t3_id, t3.name as t3_name, 
from (select * from table where name like 'a%') as t1 
cross join (select * from table where name like 'b%') as t2 
cross join (select * from table where name like 'c%') as t3

我想修改查询,使其只返回没有相似 ID 的行。

例如,第一行的 t1_id = 1, t2_id = 1 所以有两个相似的 id。这不应该出现在结果中。

【问题讨论】:

    标签: sql oracle plsql


    【解决方案1】:
        select * from (select t1.id as t1_id, t1.name as t1_name,
    t2.id as t2_id, t2.name as t2_name,
    t3.id as t3_id, t3.name as t3_name, 
    from (select * from table where name like 'a%') as t1 
    cross join (select * from table where name like 'b%') as t2 
    cross join (select * from table where name like 'c%') as t3) as ft
    where ft.t1_id<>ft.t2_id and ft.t1_id<>ft.t3_id and ft.t2_id<>ft.t3_id
    

    【讨论】:

      【解决方案2】:

      通过删除子查询来简化您的查询。然后使用where 子句进行过滤:

      select t1.id as t1_id, t1.name as t1_name,
             t2.id as t2_id, t2.name as t2_name,
             t3.id as t3_id, t3.name as t3_name, 
      from table t1 cross join
           table t2 cross join
           tablet3
      where t1.name like 'a%' and
            t2.name like 'b%' and
            t3.name like 'c%' and
            t2.id not in (t1.id) and
            t3.id not in (t1.id, t2.id);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        相关资源
        最近更新 更多