5

I have two tables table1 and table2, i need to write a select query which will list me the columns that exist in both the tables. (mysql)

I need to do for different tables (2 at a time)

Is this possible?

I tried using INFORMATION_SCHEMA.COLUMNS but am not able to get it right.

3 Answers 3

15
 SELECT a.COLUMN_NAME
 FROM INFORMATION_SCHEMA.COLUMNS a
 JOIN INFORMATION_SCHEMA.COLUMNS b
 ON a.COLUMN_NAME = b.COLUMN_NAME
 AND b.TABLE_NAME = 'table2'
 AND b.TABLE_SCHEMA = database() //or manually enter it
 WHERE a.TABLE_NAME = 'table1'
 AND a.TABLE_SCHEMA = database(); //or manually enter it
0
12

In case someone needs the opposite:
Find all columns that exist in one table, but are missing in the other:

 SELECT *
 FROM INFORMATION_SCHEMA.COLUMNS a 
 WHERE a.TABLE_NAME = 'craft_content'
 AND a.TABLE_SCHEMA = 'craftcms2'
 AND a.COLUMN_NAME NOT IN (
   SELECT b.COLUMN_NAME
   FROM INFORMATION_SCHEMA.COLUMNS b 
   WHERE b.TABLE_NAME = 'craft_content'
   AND b.TABLE_SCHEMA = 'craftcms'
 )
1
0

To find columns that are in 'table1' and not in 'table2' try this :

SELECT h.COLUMN_NAME 
FROM  INFORMATION_SCHEMA.COLUMNS h
WHERE h.TABLE_NAME = 'table1' AND 
h.COLUMN_NAME not  IN (
SELECT a.COLUMN_NAME
 FROM INFORMATION_SCHEMA.COLUMNS a
 JOIN INFORMATION_SCHEMA.COLUMNS b
 ON a.COLUMN_NAME = b.COLUMN_NAME
 AND b.TABLE_NAME = 'table2'
 AND b.TABLE_SCHEMA = database() 
 WHERE a.TABLE_NAME = 'table1'
 AND a.TABLE_SCHEMA = DATABASE() 
 )

nb: if you want the opposite you have just to switch between tables name in the query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.