0
我有一張桌子,這是一張桌子多次交叉產品的結果。現在,我可能在單行中有不同列的副本。我想知道如何編寫A!= B!= C!= D的查詢,其中A,B,C,D是列名。如何編寫SQL查詢以從同一行中選擇唯一值?如何編寫SQL查詢以從單行中獲取不同的值?
我有一張桌子,這是一張桌子多次交叉產品的結果。現在,我可能在單行中有不同列的副本。我想知道如何編寫A!= B!= C!= D的查詢,其中A,B,C,D是列名。如何編寫SQL查詢以從同一行中選擇唯一值?如何編寫SQL查詢以從單行中獲取不同的值?
您可以通過一個非常複雜的where
條款或僅僅通過投入適當的join
條件來解決此問題。
下面是一個例子:
select a.col as a, b.col as b, c.col as c, d.col as d
from table a join
table b
on b.col <> a.col join
table c
on c.col not in (a.col, b.col) join
table d
on d.col not in (a.col, b.col, c.col);
的Oracle 11g R2架構設置:
CREATE TABLE test (val) AS
SELECT LEVEL
FROM DUAL
CONNECT BY LEVEL <= 5;
查詢1:
SELECT A.val AS A_val,
B.val AS B_val,
C.val AS C_val,
D.val AS D_val
FROM test A
CROSS JOIN test b
CROSS JOIN test c
CROSS JOIN test d
WHERE A.val NOT IN (b.val, c.val, d.val)
AND B.val NOT IN (c.val, d.val)
AND C.val <> D.val
| A_VAL | B_VAL | C_VAL | D_VAL |
|-------|-------|-------|-------|
| 1 | 2 | 3 | 4 |
| 1 | 2 | 3 | 5 |
| 1 | 2 | 4 | 3 |
| 1 | 2 | 4 | 5 |
| 1 | 2 | 5 | 3 |
| 1 | 2 | 5 | 4 |
| 1 | 3 | 2 | 4 |
| 1 | 3 | 2 | 5 |
| 1 | 3 | 4 | 2 |
| 1 | 3 | 4 | 5 |
| 1 | 3 | 5 | 2 |
| 1 | 3 | 5 | 4 |
| 1 | 4 | 2 | 3 |
| 1 | 4 | 2 | 5 |
| 1 | 4 | 3 | 2 |
| 1 | 4 | 3 | 5 |
| 1 | 4 | 5 | 2 |
| 1 | 4 | 5 | 3 |
| 1 | 5 | 2 | 3 |
| 1 | 5 | 2 | 4 |
| 1 | 5 | 3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