I need to get distinct values from 3 tables.
When I perform this code:
select DISTINCT(city) from a,b,c
I get an error which says that my column 'city' is ambiguous.
Also I have tried this:
select DISTINCT(city) from a NATURAL JOIN b NATURAL JOIN c
With this code I receive nothing from my tables.
Let me show you on the example of what I am trying to do:
TABLE A TABLE B TABLE C id | city id | city id | city 1 | Krakow 1 | Paris 1 | Paris 2 | Paris 2 | London 2 | Krakow 3 | Paris 3 | Oslo 4 | Rome
And I need to get result like this
RESULTS city ---- Krakow Paris Rome London Oslo
Order of the cities is not important to me I just need to have them all, and there should be only one representation of each city.
Any idea? I was thinking to use id's
in the JOIN
but there are not connected so I can't use that.
Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.
The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns. Feel free to test this out in the editor to see what happens!
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
The UNION
keyword will return unique
records on the result list. When specifying ALL
(UNION ALL) will keep duplicates on the result set, which the OP don't want.
SELECT city FROM tableA UNION SELECT city FROM tableB UNION SELECT city FROM tableC
RESULT
╔════════╗ ║ CITY ║ ╠════════╣ ║ Krakow ║ ║ Paris ║ ║ Rome ║ ║ London ║ ║ Oslo ║ ╚════════╝
SELECT city FROM A UNION DISTINCT SELECT city FROM B UNION DISTINCT SELECT city FROM C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With