Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select distinct value from multiple tables

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.

like image 286
user123_456 Avatar asked Mar 09 '13 12:03

user123_456


People also ask

How can I get distinct values from two tables?

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.

How do you find unique records from a set of tables?

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.

Can you use select distinct with multiple columns?

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!

How can I get distinct values from two tables in MySQL?

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.


2 Answers

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 
  • SQLFiddle Demo

RESULT

╔════════╗ ║  CITY  ║ ╠════════╣ ║ Krakow ║ ║ Paris  ║ ║ Rome   ║ ║ London ║ ║ Oslo   ║ ╚════════╝ 
like image 120
John Woo Avatar answered Sep 21 '22 18:09

John Woo


SELECT city FROM A UNION DISTINCT SELECT city FROM B UNION DISTINCT SELECT city FROM C 
like image 44
James C Avatar answered Sep 21 '22 18:09

James C