An Entrepreneur, Coach, IT Consultant, Strategic Adviser, and a Traveler craving to explore and contribute to forming a better society.

Tuesday, September 1, 2009

How to compare data in two Tables in MySQL?

No comments :

Problem/Query:

How to compare data in two tables in MySQL?

Example:


Table A Table B
Customers
Customers_Backup

You may want to check if "Table A" matches all the content of "Table B". If the result is positive then go on and if the result is negative for some rows then print a log

Solution:
select (case when exists (select username from table1 where username not in (select username from table2) ) then 'Active' else 'Inactive' end as result; 

Using Case Statement in Table Columns:
select (case userstatus when 'Y' then 'Active' else 'Inactive' end) as status from users;
Note: 
Control flow statements in mysql behave differently. You have to use "END" instead of "END CASE"

Reference:
http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

http://dev.mysql.com/doc/refman/5.0/en/case-statement.html

No comments :