的多个列与表table1
与像列中选择行:具有相同的价值
name, dept, col1, col2, col3, col4, col5
我需要找到多个列相同值的行 - 例如col2, col3, col4, col5
虽然像下面这样的工作,我需要一种方法,即使对于大量的列,也不会有多个and
条件。
select *
from table1
where col2 = col3 and col3 = col4 and col4 = col5
的多个列与表table1
与像列中选择行:具有相同的价值
name, dept, col1, col2, col3, col4, col5
我需要找到多个列相同值的行 - 例如col2, col3, col4, col5
虽然像下面这样的工作,我需要一种方法,即使对于大量的列,也不会有多个and
条件。
select *
from table1
where col2 = col3 and col3 = col4 and col4 = col5
的样本数据..
CREATE TABLE foo
AS
SELECT id,
trunc(random()*10) AS col1,
trunc(random()*10) AS col2,
trunc(random()*10) AS col3,
trunc(random()*10) AS col4
FROM generate_series(1,1e6)
AS gs(id);
ALL
这方法大量缩短r,但是你仍然需要输入一次所有的列名。
SELECT * FROM foo
WHERE col1 = ALL(ARRAY[col2,col3,col4]);
SELECT format(
'SELECT * FROM foo WHERE %s;',
(
SELECT string_agg('col1 = col'||id, ' AND ')
FROM generate_series(2,4) AS id
)
);
使用'ALL'是去这里的方法。为什么我之前没有想到这一点? ;-) – AKS
请尝试以下查询
SELECT * FROM table1 WHERE col2 IN(col3,col4,col5) OR col3 IN(col2,col4,col5) OR col4 IN(col3,col2,col5) OR col5 IN(col3,col4,col2);
如果需要任何改变让我知道。
该查询返回_some_字段相等的行; OP希望_all_字段的行相等。 – Dario
你可以做这样的事情:
SELECT * FROM table1
WHERE (
SELECT COUNT(*) FROM (
SELECT DISTINCT UNNEST(ARRAY[col2, col3, col4, col5])
) tmp
) = 1;
的步骤在这里分解:
使用'ALL'或生成SQL是简单的解决方案。查看我的答案的例子。 –