I have a table named ‘fiction’ created in MySQL. The table looks like this
fiction:
id | name | gender | image | browser | os |
---|---|---|---|---|---|
1 | chris | male | 1 | 0 | ios |
2 | emma | female | 1 | 1 | ios |
3 | james | male | 0 | 0 | android |
4 | lucas | male | 1 | 0 | android |
5 | amelia | female | 0 | 1 | ios |
6 | olivia | female | 1 | 0 | ios |
What I want to do is to retrieve the names of the columns where the records in the ‘gender’ column have the value ‘male’, and all other columns have the same value. For example, If I run this code:
SELECT * FROM fiction WHERE gender = "male";
The output will be:
id | name | gender | image | browser | os |
---|---|---|---|---|---|
1 | chris | male | 1 | 0 | ios |
3 | james | male | 0 | 0 | android |
4 | lucas | male | 1 | 0 | android |
As you can see, the ‘browser’ column has a common value of ‘0’ in all records. So I want this column name, ‘browser’. Another example:
SELECT * FROM fiction WHERE gender = "female";
Output:
id | name | gender | image | browser | os |
---|---|---|---|---|---|
2 | emma | female | 1 | 1 | ios |
5 | amelia | female | 0 | 1 | ios |
6 | olivia | female | 1 | 0 | ios |
As you can see here, the ‘os’ column has a common value in all of them. I need an SQL statement that will show me these common columns.
I used GROUP BY and HAVING expressions, but as you can guess, they didn’t solve my problem. I think I need to do something related to the information_schema table.
3
Answers
As you don’t explain what exact outcome you want, i show you for an example how to do it and then you can extend it to your purposes
Then basic idea is that the group can have only the count of distinct values of 1, if you are searching for common values
The query bleow finds also all common columns
fiddle
To give you an idea:
Count distinct values, and if it is equal to 1, then returns desired name (column name for your case), and if it is not returns "-". Finally we add the outputs together.
The output is:
os,-,-
If you are sure that you have only one common column, you can change "-" with an empty string and remove the ‘,’ from CONCAT. So query will be like:
And the ouput is:
os
.Solution for
female
is the same, just replace ‘mail’ by ‘female’.see: DBFIDDLE