简体   繁体   English

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

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

Here's the simple query: 这是简单的查询:

SELECT status FROM tbl_pedidos_produtos WHERE status = 4;

This, obviously, brings me only the entries whose status equals to 4, but in this manner I can't test if ALL entries have status 4. How can I do something like this? 显然,这只给我带来状态等于4的条目,但是这样我就无法测试所有条目是否都有状态4.我怎么能这样做?

SELECT status FROM tbl_pedidos_produtos WHERE status OF ALL = 4;

Simply, just get COUNT(*) of the rows those doesn't have status = 4 简单地说,只获取那些没有status = 4的行的COUNT(*)

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

If it's greater than 0, that means you have at least one row which has status != 4. 如果它大于0,则表示您至少有一行具有状态!= 4。

You can do this using aggregation. 您可以使用聚合执行此操作。 Here is one way: 这是一种方式:

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

Another way that might be a bit less obvious: 另一种可能不太明显的方式:

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

If you don't have null values in there, you can do that in a single query by selecting all distinct status values, counting them, then make sure that adds up to 1. Like this: 如果你没有空值,你可以在一个查询中通过选择所有不同的状态值,计算它们,然后确保最多加1来完成。像这样:

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

If you do have null values (ie, a product without a status value for some reason), then you'll need to filter them out first. 如果您确实有空值(即由于某种原因没有状态值的产品),那么您需要先将它们过滤掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM