如何检查所有行是否具有相同的列值


How can I check if all rows have the same column value?

下面是一个简单的查询:

SELECT status FROM tbl_pedidos_produtos WHERE status = 4;

很明显,这只会给我带来状态等于4的条目,但以这种方式,我无法测试所有条目是否都具有状态4。我怎么能做这样的事?

SELECT status FROM tbl_pedidos_produtos WHERE status OF ALL = 4;

简单地说,只需获取不具有状态=4的行的COUNT(*)

SELECT COUNT(*) FROM tbl_pedidos_produtos WHERE status != 4;

如果它大于0,则意味着您至少有一行具有状态!=4.

您可以使用聚合来实现这一点。这里有一种方法:

select (max(status) = 4 and min(status) = 4 and status is not null) as AllSameFlag
from tbl_pedidos_produtos;

另一种可能不那么明显的方式:

select (count(*) = 0) as AllSameFlag
from tbl_pedidos_produtos
where status <> 4 or status is null

如果没有空值,可以在一个查询中选择所有不同的状态值,对其进行计数,然后确保加起来为1。像这样:

SELECT (SELECT COUNT(DISTINCT `status`) from `tbl_pedidos_produtos`)  = 1;

如果您确实有空值(即,由于某种原因没有状态值的产品),那么您需要首先将其过滤掉。