I want to select each available entry for each column once. This problem was solved with
SELECT DISTINCT a from my_table
UNION
SELECT DISTINCT b from my_table
UNION
SELECT DISTINCT c from my_table
UNION
SELECT DISTINCT d from my_table
in this question: MySQL SELECT DISTINCT multiple columns
I want to go further and use the same WHERE
statements on each subquery. Is there any way without defining the WHERE
each time? My current query would look like this:
SELECT DISTINCT a from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
UNION
SELECT DISTINCT b from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
UNION
SELECT DISTINCT c from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
UNION
SELECT DISTINCT d from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
All parameters don't have to be given, I just want to show the maximum that has to be possible. Is there any way to write this shorter?
I use PHP with doctrine, if that is any help.
Thanks in advance!
Example: my_table:
a | b | c | d
-----+-----+-----+-----
a | 0 | . | ab
b | 0 | - | ag
a | 1 | . | cfd
c | 1 | . | b
a | 1 | - | ab
c | 1 | - | cfd
should give this result (without where statement):
a | b | c | d
-----+-----+-----+-----
a | 0 | . | ab
b | 1 | - | ag
c | | | cfd
| | | b
And with WHERE b=0
statement:
a | b | c | d
-----+-----+-----+-----
a | 0 | . | ab
b | | - | ag
EDIT: changed subqueries to UNION and made the data types fit to the example