简体   繁体   English

MySQL - 选择每行的列是否为TRUE?

[英]MySQL - Select if the column of every row is TRUE?

I am querying two tables via a JOIN query to determine if every row in the result set's approved column is TRUE . 我通过JOIN查询查询两个表,以确定结果集的approved列中的每一行是否为TRUE

SELECT
    `approvals`.`approved`
FROM `sign_ins`
RIGHT JOIN `approvals` ON
    `sign_ins`.`user` = `approvals`.`user`;

This will return a result set of boolean values for each user, eg 这将返回每个用户的布尔值的结果集,例如

1
0
0
1
1

My PHP code iterates through these rows and determines if all are approved simply by returning false and breaking a loop if any of these values are 0 . 我的PHP代码遍历这些行并确定是否所有都被批准只是返回false并且如果这些值中的任何值为0则断开循环。 However, I think it would be more performant and optimal if iterating through the result set wasn't necessary; 但是,如果没有必要迭代结果集,我认为它会更高效和最佳; after all, I really only care about one thing: TRUE if all the rows' approved value are TRUE ; 毕竟,我真的只关心一件事: TRUE ,如果所有行approved值是TRUE ; else, FALSE . 否则, FALSE

Can I do this with a MySQL query? 我可以使用MySQL查询吗?

Thanks. 谢谢。

If you just want all TRUE results, ask for it! 如果您只想要所有真实的结果,请求它!

SELECT
    `approvals`.`approved`
FROM `sign_ins`
RIGHT JOIN `approvals` ON
    `sign_ins`.`user` = `approvals`.`user`;
WHERE `approvals`.`approved` = 1

I would just COUNT() all rows and compare that to the SUM() of the approved column. 我只需COUNT()所有行,并将其与已批准列的SUM()进行比较。 If they match, then all rows were 1. If they don't, then there was at least one 0. 如果它们匹配,那么所有行都是1.如果它们不匹配,那么至少有一个0。

Using COUNT(approved) will not count NULL values, so you don't need to compensate for that. 使用COUNT(approved)不会计算NULL值,因此您无需对此进行补偿。

Your query would look like: 您的查询将如下所示:

SELECT (CASE WHEN COUNT(approved)=SUM(approved) THEN 1 ELSE 0 END)
FROM sign_ins
RIGHT JOIN approvals USING (user)

This should return 1 for TRUE and 0 for FALSE. 这应该返回1表示TRUE,0表示FALSE。

Here was my solution. 这是我的解决方案。 I use the MIN function to select the smallest value, so it should return 0 if there are any FALSE values present. 我使用MIN函数来选择最小值,因此如果存在任何FALSE值,它应该返回0 Also, since it's not a full join, a sign in that is not present in the approvals table should be assumed to be unapproved; 此外,由于它不是完整的连接,因此应认为approvals表中不存在的登录未经批准; therefore, I used IFNULL to provide a default FALSE value. 因此,我使用IFNULL提供默认的FALSE值。

Here's a complete example of my query (minus some date logic): 这是我的查询的完整示例(减去一些日期逻辑):

SELECT
    MIN(IFNULL(`approvals`.`approved`, FALSE))
FROM `sign_ins`
LEFT JOIN `approvals` ON
    `sign_ins`.`user` = `approvals`.`user`;

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

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