简体   繁体   中英

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?

SELECT status FROM tbl_pedidos_produtos WHERE status OF ALL = 4;

Simply, just get COUNT(*) of the rows those doesn't have status = 4

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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