在SQL中生成条件组合

时间:2018-07-28 22:19:20

标签: sql oracle plsql

我有下表:

╔═══╦══════════════╦═════════════╗
║   ║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

enter image description here

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

可能实际上并不需要子查询。

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 AS t1
JOIN table AS t2 ON t2.name LIKE 'b%'
JOIN table AS t3 ON t3.name LIKE 'c%'
WHERE t1.name LIKE 'a%'
  AND t1.id <> t2.id 
  AND t1.id <> t3.id 
  AND t2.id <> t3.id

答案 2 :(得分:0)

通过删除子查询来简化查询。然后使用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);