我試圖為我的 PostgreSQL 資料庫創建 SQL 問題。我的表格如下所示:
id | column1 | column2| column3 | column4
1 | 1 | 2 | 3 | 1
2 | 21 | 22 | 23 | 5
3 | 31 | 22 | 32 | 6
4 | 54 | 43 | 45 | 4
5 | 43 | 23 | 34 | 4
6 | 43 | 54 | 43 | 2
7 | 54 | 52 | 53 | 8
8 | 21 | 2211 | 43 | 4
9 | 43 | 33 | 45 | 9
10 | 87 | 62 | 11 | 3
我嘗試撰寫問題以僅回傳所選列的唯一值,例如column1:
id | column1 | column2| column3 | column4
1 | 1 | 2 | 3 | 1
2 | 21 | 22 | 23 | 5
3 | 31 | 22 | 32 | 6
8 | 21 | 2211 | 43 | 4
10 | 87 | 62 | 11 | 3
我的請求:
SELECT id, column1, column2, column3, column4
FROM test AS T
WHERE T.column1 != T.column2
OR T.column1 != T.column3
作為回應,我得到了整個表,而不是唯一的記錄。
有人可以告訴我為什么這不起作用并解釋如何撰寫一個可以作業的查詢。
uj5u.com熱心網友回復:
如果我理解正確,您希望它們在 column1 中的值不會出現在任何其他行的 column2、column3 或 column4 中的行。
為此,您可以執行子查詢來檢查每一行與其他每一行。
select *
from test t1
where not exists (
select id
from test t2
where t2.id <> t1.id and (
t2.column2 = t1.column1 or
t2.column3 = t1.column1 or
t2.column4 = t1.column1
)
)
示范
請注意,需要檢查不同列的唯一性表明 column1、column2、column3 和 column4 實際上是相同型別值的串列。將值存盤在連接表中會更好。
create table test (
id bigserial primary key
);
create table test_stuff (
test_id bigint not null references test,
value integer not null
);
insert into test values (1);
insert into test_stuff values (1, 1), (1,2), (1,3), (1,1);
uj5u.com熱心網友回復:
它會是這樣的:
SELECT *
FROM TEST
WHERE
COLUMN1 NOT IN (
SELECT COLUMN2
FROM TEST
)
AND COLUMN1 NOT IN (
SELECT COLUMN3
FROM TEST
)
你可以在這里試試:https ://www.db-fiddle.com/f/mmMr3vz2JHvfBabu62Si79/0
uj5u.com熱心網友回復:
描述與預期結果不符。話雖如此,以下查詢應該會產生預期的結果。它查找在第 1 列中沒有重復的所有行:
select *
from t
where not exists (
select *
from t as x
where x.column1 = t.column1 and x.id <> t.id
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/441426.html
標籤:sql 数据库 PostgreSQL
上一篇:將包含不同數量值的列拆分為多個列,SQLServer
下一篇:如何根據條件增加列的值?
