DB Where条件基于2列的字母顺序比较

DB Where Condition Based on Alphabetical Comparison of 2 columns

我有SQL查询自加入产品table

编号 | product_name

我需要做2套:

A vs B 和 B vs A.

A vs B 表示按字母顺序先到先得。

B vs A 表示按字母顺序先到后。

下面给出了 a's id 小于 b'id 的所有组合,但我需要先按字母顺序排列

SELECT
a.product_name || b.product_name
from 
products a
JOIN products b ON a.id != b.id  -- same product combination not needed 
WHERE
   a.id < b.id   

示例数据

1 | Apple
2 | Apricots
3 | Bananas
4 | Blueberries
5 | Cherries
6 | Cucumbers
7 | Dates
8 | Dragon Fruit
9 | Eggfruit
10 | Mango

Total set will have 每个水果都会与每个没有where条件的组合。

我需要 2 个独立的套装。

第一组将有:A vs B - 按字母顺序排在第一位

Apple Vs Apricots

第二组将有:B 对 A - 按字母顺序最后

Apricots Vs Apple 

您可以使用两个查询来获得您想要的两个结果集,它们基本相同,只是第二个查询的 JOIN 条件发生了变化:

SELECT a.product_name || ' - ' ||  b.product_name AS products
FROM products a
JOIN products b ON a.product_name < b.product_name
ORDER BY a.product_name, b.product_name

对于第二个查询,JOIN 条件是:

JOIN products b ON a.product_name > b.product_name

输出(第一次查询):

Apple - Apricots
Apple - Bananas
Apple - Blueberries
...
Dragon Fruit - Eggfruit
Dragon Fruit - Mango
Eggfruit - Mango

输出(第二次查询):

Apricots - Apple
Bananas - Apple
Bananas - Apricots
...
Mango - Dates
Mango - Dragon Fruit
Mango - Eggfruit

Demo on SQLFiddle