I have 4 tables, filled with some example data
user table
id | name | idAddress |
------------------------
1 | Bernd | 1 |
2 | Max | 2 |
3 | Tom | 3 |
4 | Bob | 4 |
5 | Alice | 5 |
address
id | country | zip |
----------------------
1 | DE | 39213 |
2 | CH | 13847 |
3 | NL | 38472 |
4 | DE | 94872 |
5 | MT | 54682 |
6 | US | 4682 |
7 | DE | 45853 |
8 | NA | 12144 |
orga2Address
idOrga | idAddress |
------------------
1 | 6 |
1 | 7 |
2 | 7 |
2 | 8 |
orga2User
idUser | idOrga |
-----------------
1 | 1 |
1 | 2 |
2 | 1 |
3 | 2 |
4 | 2 |
I want to select all user names that have address in 'DE' in the user table or that are in an orga which has an address in 'DE' in orga2Address.
I was able to get the result with the UNION command like this (see this SQLFiddle):
SELECT `name`, `country` FROM (SELECT `user`.`name`, `address`.`country` from `user`
INNER JOIN `address` ON `user`.`idAddress` = `address`.`id`
UNION
SELECT `user`.`name` from `user`
INNER JOIN `orga2User` `o2U` ON `o2U`.`idUser` = `user`.`id`
INNER JOIN `orga2Address` `o2A` ON `o2A`.`idOrga` = `o2U`.`idOrga`
INNER JOIN `address` `a` ON `a`.`id` = `o2A`.`idAddress`) as `U` WHERE `U`.`country`="DE";
The result
name |
--------
Bernd |
Max |
Tom |
Bob |
Is there a quicker and better way to get the wanted result?