从不同的表创建组合

时间:2019-01-17 23:47:12

标签: mysql sql

我有下表:

表1

name, weight
A, 4
B, 2
C, 1

表2

name, weight
AA, 4
BB, 2
CC, 1

表3

name, weight
AAA, 4
BBB, 2
CCC, 1

我想创建表格的所有组合,然后按总重量(重量总和)对其进行排序。例子

A, AA, AAA, 12
A, BB, AAA, 10
A, CC, AAA, 9
A, AA, BBB, 10
A, BB, BBB, 8
A, CC, BBB, 7
A, AA, CCC, 9
A, BB, CCC, 7
A, CC, CCC, 6
...
C, CC, CCC, 3

SQL是否可能?

2 个答案:

答案 0 :(得分:3)

交叉连接是可能的

select 
  t1.name as name1, 
  t2.name as name2, 
  t3.name as name3, 
  t1.weight + t2.weight + t3.weight as weight
from table1 t1,
  table2 t2,
  table3 t3

答案 1 :(得分:2)

您正在寻找CROSS JOIN

select  
  t1.name as name1, 
  t2.name as name2, 
  t3.name as name3,
  t1.weight + t2.weight + t3.weight as weight
from table1 t1
cross join table2 t2
cross join table3 t3

如果您的weight列中可能包含null个值,则需要使用coalesce函数来避免将null作为输出并将这些值视为0

select 
  t1.name as name1, 
  t2.name as name2, 
  t3.name as name3, 
  coalesce(t1.weight,0) + coalesce(t2.weight,0) + coalesce(t3.weight,0) as weight
from table1 t1
cross join table2 t2
cross join table3 t3