Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

I am querying two tables via a JOIN query to determine if every row in the result set's approved column is 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, e.g.

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. 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; else, FALSE.

Can I do this with a MySQL query?

Thanks.

like image 853
M Miller Avatar asked Nov 02 '14 23:11

M Miller


People also ask

How do you search for a string in all fields of every table in a MySQL database?

There is a Schemas tab on the side menu bar, click on the Schemas tab, then double click on a database to select the database you want to search. Then go to menu Database - Search Data, and enter the text you are searching for, click on Start Search.

How do you set a boolean to true in MySQL?

You can update boolean value using UPDATE command. If you use the BOOLEAN data type, MySQL internally convert it into tinyint(1). It can takes true or false literal in which true indicates 1 to tinyint(1) and false indicates 0 to tinyint(1).


2 Answers

I would just COUNT() all rows and compare that to the SUM() of the approved column. If they match, then all rows were 1. If they don't, then there was at least one 0.

Using COUNT(approved) will not count NULL values, so you don't need to compensate for that.

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.

like image 77
wolfgangwalther Avatar answered Oct 19 '22 17:10

wolfgangwalther


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
like image 2
kair Avatar answered Oct 19 '22 18:10

kair