检查所有行是否相同

时间:2019-01-10 08:56:17

标签: sql postgresql

我有一个选择查询,该查询返回多行,并且我想检查所有行是否相同。像这样:

anything_other_than(123) in (select id from foo)

因此,如果select id from foo返回111,222,123,333,则上述语句为false;如果select id from foo返回123,123,123,则为true。我该如何实现?

4 个答案:

答案 0 :(得分:5)

一个简单的解决方案是使用= ALL运算符:

SELECT 123 = ALL (SELECT id FROM foo);

一旦找到第一个不匹配的值,该解决方案还将停止扫描结果。

答案 1 :(得分:3)

另一种选择是将EXISTS与where条件一起使用:

select not exists (select *
                   from the_table
                   where id <> 123);

答案 2 :(得分:1)

运行此:

select count(distinct id) = 1 and count(*) > 1 from foo;

count(distinct id)将返回1,如果所有行都相同
count(*)将返回总行数。
如果返回true,则说明您有多于1行,并且所有行都相同。

答案 3 :(得分:-1)

您可以使用类似这样的内容-

select x, IF(x > 1, "FALSE", "TRUE") from 
(SELECT count(distinct(A.id)) as x FROM foo as A) as B;

请参考此https://www.w3schools.com/sql/func_mysql_if.asp

相关问题