I have a table entries with three columns: id, name, display_name.
I need to write a query with join, which will check how many display_names there is for each name and display only those names, which have multiple display_names.
This should be fairly simple to write with joins. Before I used next query:
SELECT e1.name
FROM entries e1
WHERE (
SELECT COUNT(DISTINCT e2.display_name)
FROM entries e2
WHERE e2.name = r1.name
) > 1;
You don’t need a join.
Note that you can use an alias in a having clause, so borrowing from @Scorpi0 and @Widor you can also do:
The reason this is allowed is that
havingis evaluated after all the other stuff in the select is done. By that time the contents of the alias will be known.You cannot use this alias in the
WHEREclause because that runs (or may run) before MySQL knows what in the alias.