Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Inner Join Query To Get Records Not Present in Other Table

Tags:

mysql

I have table 1, all_countries, as follows-

id   |  country
------------------
1    |  USA
2    |  China
3    |  India
4    |  France
5    |  UK
6    |  Australia

and I also have table 2, supported_countries, as -

id   |  country
------------------
1    |  USA
2    |  China

Now I need a query that would give me result that includes all countries that ARE NOT supported

So as per above example I should get

India
France
UK
Australia

I am using the following query -

SELECT ac.country FROM all_countries ac INNER JOIN supported_countries sc ON sc.country_name != ac.country_name

It works fine, except when supported_countries table is empty, it doesn't show any records. How to achieve this result?

like image 848
skos Avatar asked Mar 31 '12 09:03

skos


People also ask

How do you get records which are not in another table in MySQL?

We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do you select all records from one table that do not exist in another table Excel?

select [ selecting columns] From table1 Right OUTER JOIN table2 ON(table1. SQL> select e. select [ selecting columns] From table1 Right OUTER JOIN table2 ON(table1. select column_name from table 1 full outer join table 2 on(connection); here all the data from table 1 and table 2 will get retrieved.


1 Answers

A LEFT JOIN will do that elegantly;

SELECT a.* 
FROM all_countries a
LEFT JOIN supported_countries s
  ON a.country = s.country
WHERE s.id IS NULL;

Demo here.

like image 84
Joachim Isaksson Avatar answered Oct 11 '22 18:10

Joachim Isaksson