我有一个表,它给出了两个项目之间的值。该表具有以下列:
itemA | itemB | value
1 | 2 | 125
1 | 3 | 56
3 | 2 | 78
2 | 4 | 24
4 | 1 | 994
3 | 4 | 7
我强调对称值不会重复。例如,现在存在 itemA = 2 和 itemB = 1 且值 = 125 的行,因为该数据已经存储在 itemA = 1 和 itemB = 2 的情况下。
现在我想获取项目 1、2 和 3 之间的所有值,但也包含对称值。SQL 结果集中类似的东西:
itemA | itemB | value
1 | 2 | 125
1 | 3 | 56
2 | 1 | 125
2 | 3 | 78
3 | 1 | 56
3 | 2 | 78
我通过以下 SQL 查询成功地做到了这一点:
select itemA as iA, itemB as iB, value
from table
where itemA in (1,2,3)
and itemB in (1,2,3)
union all
select itemB as iA, itemA as iB, value
from table
where itemA in (1,2,3)
and itemB in (1,2,3)
order by iA, iB;
但是,有人对我说 UNION 运算符是性能杀手,而该表实际上有超过 1 亿行。但是经过数小时的头脑风暴,我没有找到另一种方法来获得它。拜托,您能否看到一个更好、性能更高的 SQL 查询来获取此结果集。
先感谢您